对String []数组的数组列表进行排序

nat*_*and 6 java sorting arraylist comparator

我正在阅读一个.csv类似excel中的电子表格的文件.有一定数量的列,由文件确定,我使用该.split(",")方法将每一行读入字符串数组.然后我把它放到一个数组列表中,这样它就可以保存所有的字符串数组而不给它一个特定的大小.但是,当我使用时对数组列表进行排序时Collections.sort(),程序会中断.问题是什么?这是我要排序的代码:

Collections.sort(stringList, new Comparator < String[] > () {
    public int compare(String[] strings, String[] otherStrings) {
        return -1 * (strings[sortNum].compareTo(otherStrings[sortNum]));
    }
});
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 7

两点:

  • 不要将结果乘以compare-1以反转比较.Integer.MIN_VALUE * -1还在Integer.MIN_VALUE.相反,颠倒比较本身的顺序
  • 我的猜测是你实际上有一些没有足够列的行.也许你应该把那些放在最后?

就像是:

Collections.sort(stringList, new Comparator < String[] > () {
    public int compare(String[] x1, String[] x2) {
        if (x1.length > sortNum && x2.length > sortNum) {
            return x2[sortNum].compareTo(x1[sortNum]); 
        }
        if (x1.length > sortNum) {
            return 1;
        }
        if (x2.length > sortNum) {
            return -1;
        }
        return x2.length - x1.length;
    }
});
Run Code Online (Sandbox Code Playgroud)

或者,首先过滤列表以确保所有行都有足够的列.