对 String[] 数组的数组列表进行排序
我正在读取 .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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
两点:
compare
的结果乘以-1来反转比较。Integer.MIN_VALUE * -1
仍然是Integer.MIN_VALUE
。相反,颠倒比较本身的顺序例如:
或者,首先过滤列表以绝对确保所有行都有足够的列。
Two points:
compare
by -1 to reverse a comparison.Integer.MIN_VALUE * -1
is stillInteger.MIN_VALUE
. Instead, reverse the order of the comparison itselfSomething like:
Alternatively, filter your list first to make absolutely sure that all rows have enough columns.
那么,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?
尝试使用这个
首先你的类比较器和构造函数:
并在你的代码中
希望这对你有用
Try using this
First your class comparator with a constructor:
and in your code
Hope that works for you
共享代码,以防有人需要对多列进行排序。
Sharing code in case someone need to do the sort on multiple columns.
我怀疑您可能在引用“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. :)
您可以为空“单元格”提供默认值:
you can provide default values for empty "cells":