如何对包含空元素的对象数组进行排序? [英] How to sort an array of objects containing null elements?
问题描述
在我的程序中创建了一个固定长度 [7] 对象的数组 fClasses
,每个对象是一个包含 3 个 Strings
的类 FClass
>、一个 int
和一个 int[]
.这些值是从 .txt 文件中读取的,并根据 int
的值添加到数组的特定索引中..txt 文件中的条目少于数组中的索引,因此数组最终看起来像这样:
In my program an array fClasses
of fixed length [7] of objects is created, each object is a class FClass
that contains 3 Strings
, an int
, and an int[]
. These values are read from a .txt file and added to a specific index of the array based on the value of the int
. There are less entries in the .txt file then there are indices in the array so the array ends up looking something like this:
fClasses[0] { str1, str2, str3, int1, int [] {1,2,3,4,5}}
fClasses[1] { str1, str2, str3, int1, int [] {1,2,3,4,5}}
fClasses[2] { str1, str2, str3, int1, int [] {1,2,3,4,5}}
fClasses[3] null
fClasses[4] null
fClasses[5] { str1, str2, str3, int1, int [] {1,2,3,4,5}}
fClasses[6] { str1, str2, str3, int1, int [] {1,2,3,4,5}}
稍后在程序中,我需要根据 int[]
中 ints
的平均值对数组进行排序.我有一个返回它的工作方法,但是当我尝试使用 compareTo
和 Arrays.sort
对数组进行排序时,我得到了一长串以这些开头的错误:
Later in the program I need to sort the array based on the average of the ints
in the int[]
. I have a working method to return this but when I try to sort the array using compareTo
and Arrays.sort
I get a long list of errors starting with these:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at java.util.ComparableTimSort.countRunAndMakeAscending(Unknown Source)
at java.util.ComparableTimSort.sort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at FProg.sortClasses(FProg.java:228)
我的 compareTo
方法如下所示,它位于实现 Comparable
的类中:
My compareTo
method looks like this and it's located in a class that implements Comparable
:
public int compareTo(FClass other)
{
if (other == null || this.avg == other.avg)
{
return 0;
}
else if (this.avg < other.avg)
{
return -1;
}
else
{
return 1;
}
}
我正在尝试调用此方法进行排序:
And I'm trying to call this method to do the sorting:
public void sortClasses()
{
Arrays.sort(fClasses, 0, MAX_CLASSES);
}
我已经用 .txt 文件对其进行了测试,该文件包含足够的条目来填充数组,并且在这种情况下排序工作正常,所以我相信我遇到的问题是我的排序方法无法对数组进行排序其中的空元素.有什么办法可以实现吗?
I have tested it with a .txt file that contains enough entries to fill the array and the sort works correctly in that case, so I believe the problem I'm having is that my sort method can't sort an array with null elements in it. Is there any way this can be achieved?
推荐答案
您需要自己的 Comparator
实现并检查空值并返回 0
You need your own Comparator
implementation and check for nulls and return 0
Arrays.sort(fClasses, new Comparator<FClass>() {
@Override
public int compare(FClass o1, FClass o2) {
if (o1 == null && o2 == null) {
return 0;
}
if (o1 == null) {
return 1;
}
if (o2 == null) {
return -1;
}
return o1.compareTo(o2);
}});
这篇关于如何对包含空元素的对象数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!