如何制作按第二个字符排序的字符串数组列表

问题描述 投票:0回答:1

我想对 String 的 arrayList 进行排序,并使用可比较接口和 CompareTo 方法按第二个字符排序。

public class Main implements Comparable<String>{
    public static void main(String[] args){
    
        ArrayList<String> arr = new ArrayList<>();
    
        arr.add("abc");
        arr.add("cde");
        arr.add("ace");
        arr.add("crf");
        arr.add("pgq");
        arr.add("zav");
    
        Collections.sort(arr);
    }
   
    @Override
    public int compareTo(String temp){
        what should I write here;
    }
}

我期待的结果是:

zav、abc、ace、cde、pqq、crf;

java comparable
1个回答
1
投票

您可以修改compareTo方法如下:

@Override
public int compareTo(String s) {
    // Check if the length is at least 2 to compare the second character
    if (this.length() >= 2 && s.length() >= 2) {
        // Compare the second characters
        return Character.compare(this.charAt(1), s.charAt(1));
    } else {
        // If either string is too short, default to normal string comparison
        return this.compareTo(s);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.