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

发布于 2024-12-03 05:31:57 字数 454 浏览 1 评论 0原文

我正在读取 .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]));
    }
});

I am reading in a .csv file sort of like a spreadsheet in excel. There are a certain number of columns, determined by the file, and I read each line into a string array using the .split(",") method. I then put this into an array list so it can hold all of the string arrays without giving it a specific size. However, when I go to sort the array list using Collections.sort(), the program breaks. What could the problem be? Here is my code to sort:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

‘画卷フ 2024-12-10 05:31:57

两点:

  • 不要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;
    }
});

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

Two points:

  • Don't multiply the result of compare by -1 to reverse a comparison. Integer.MIN_VALUE * -1 is still Integer.MIN_VALUE. Instead, reverse the order of the comparison itself
  • My guess is that you've actually got some rows without enough columns. Perhaps you should put those at the end?

Something like:

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;
    }
});

Alternatively, filter your list first to make absolutely sure that all rows have enough columns.

简单气质女生网名 2024-12-10 05:31:57

那么,strings[sortNum] 或 otherStrings[sortNum] 都可能超出范围。您需要做一些检查来防止这种情况发生。此外,strings[sortNum] 或 otherStrings[sortNum] 可以为 null。我敢打赌您正在遇到这两件事之一。调用堆栈表明什么?

Well, either strings[sortNum] or otherStrings[sortNum] could be out of bounds. You need to do some checks to prevent that. Also, strings[sortNum] or otherStrings[sortNum] could be null. I bet you're running into one of these 2 things. What does the call stack indicate?

々眼睛长脚气 2024-12-10 05:31:57

尝试使用这个

首先你的类比较器和构造函数:

public class MyStringArrayComparator implements Comparator<String[]>{

       Integer sortNum;

       public MyStringComparator(Integer index) {
              sortNum = index;
       }

       @Override
       public int compare(String[] strings, String[] otherStrings) {
              return -1*(strings[sortNum].compareTo(otherStrings[sortNum]));
       }
}

并在你的代码中

Collections.sort(stringList,new MyStringArrayComparator<String[]>(index));

希望这对你有用

Try using this

First your class comparator with a constructor:

public class MyStringArrayComparator implements Comparator<String[]>{

       Integer sortNum;

       public MyStringComparator(Integer index) {
              sortNum = index;
       }

       @Override
       public int compare(String[] strings, String[] otherStrings) {
              return -1*(strings[sortNum].compareTo(otherStrings[sortNum]));
       }
}

and in your code

Collections.sort(stringList,new MyStringArrayComparator<String[]>(index));

Hope that works for you

羁客 2024-12-10 05:31:57

共享代码,以防有人需要对多列进行排序。

public final class ArrayComparatorWithIndex<T extends Comparable<T>> implements Comparator<T[]>
{
    private final int[] indexToSort;

    public ArrayComparatorWithIndex(int[] indexToSort)
    {         
        if(indexToSort == null || indexToSort.length == 0){
            throw new IllegalArgumentException("Index to use for sorting cannot be null or empty.");
        }
        this.indexToSort = indexToSort;
    }

    @Override
    public int compare(T[] str, T[] otherStr)
    { 
        int result= 0;
        for (int index : indexToSort)
        {
            result= str[index].compareTo(otherStr[index]);
            if (result != 0){
                break;
            }
        }
        return result;
    }
}

//Example how to use it:  
int[] indexForSorting= new int[] { 1, 3 };
Collections.sort(stringList, new ArrayComparatorWithIndex<String>(indexForSorting));

Sharing code in case someone need to do the sort on multiple columns.

public final class ArrayComparatorWithIndex<T extends Comparable<T>> implements Comparator<T[]>
{
    private final int[] indexToSort;

    public ArrayComparatorWithIndex(int[] indexToSort)
    {         
        if(indexToSort == null || indexToSort.length == 0){
            throw new IllegalArgumentException("Index to use for sorting cannot be null or empty.");
        }
        this.indexToSort = indexToSort;
    }

    @Override
    public int compare(T[] str, T[] otherStr)
    { 
        int result= 0;
        for (int index : indexToSort)
        {
            result= str[index].compareTo(otherStr[index]);
            if (result != 0){
                break;
            }
        }
        return result;
    }
}

//Example how to use it:  
int[] indexForSorting= new int[] { 1, 3 };
Collections.sort(stringList, new ArrayComparatorWithIndex<String>(indexForSorting));
薄荷→糖丶微凉 2024-12-10 05:31:57

我怀疑您可能在引用“sortNum”变量时遇到关闭问题。请参阅 Jon Skeet 的闭包文章获取一些指导,尽管它涉及 C# 中的闭包,但它应该仍然具有相关性。即使您没有遇到这个问题,这也是一本好书。 :)

I suspect you might have a closure problem in reference to the 'sortNum' variable. See Jon Skeet's closure article for some guidance, even though it deals with closures in C# it should still be relevant. Even if you don't have this issue, it's a good read. :)

寄风 2024-12-10 05:31:57

您可以为空“单元格”提供默认值:

            public int compare(String[] strings, String[] otherStrings) {
                String one, other;
                one = other = ""; // default value
                if (sortNum<strings.length && strings[sortNum] != null) {
                    one = strings[sortNum];
                }
                if (sortNum<otherStrings.length && otherStrings[sortNum] != null) {
                    other = otherStrings[sortNum];
                }
                return -1 * (one.compareTo(other));
            }

you can provide default values for empty "cells":

            public int compare(String[] strings, String[] otherStrings) {
                String one, other;
                one = other = ""; // default value
                if (sortNum<strings.length && strings[sortNum] != null) {
                    one = strings[sortNum];
                }
                if (sortNum<otherStrings.length && otherStrings[sortNum] != null) {
                    other = otherStrings[sortNum];
                }
                return -1 * (one.compareTo(other));
            }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文