且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何对包含字符串数组的arraylist进行排序?

更新时间:2022-11-16 13:51:26

一个简单的自定义比较器应该可以解决问题.

A simple custom comparator should do the trick.

唯一棘手的事情是确保您没有索引到空数组中

The only tricky thing is making sure that you are not indexing into an empty array:

Collections.sort(allWordList, new Comparator<String[]>() {
    public int compare(String[] o1, String[] o2) {
        if (o1.length == 0) {
            return o2.length == 0 ? 0 : -1;
        }
        if (o2.length == 0) {
            return 1;
        }
        return o2[0].compareTo(o1[0]);
    }
});