我在这里看到了与Timsort错误有关的各种问题,并根据它应用了代码更改。但是没有一个能让我产生结果。请帮助我解决我的错误。 代码:
public int compare(Record record1, Record record2) {
int indexOfRecord1=records.indexOf(record1);
int indexOfRecord2=records.indexOf(record2);
Integer sortIndexOfRecord1=indexToSortIndexMap.get(indexOfRecord1);
Integer sortIndexOfRecord2=indexToSortIndexMap.get(indexOfRecord2);
//Option 1: Throws same Timsort error:
if(sortIndexOfRecord1!=null && sortIndexOfRecord2!=null){
return sortIndexOfRecord1.compareTo(sortIndexOfRecord2);
}else{
return (sortIndexOfRecord1==null && sortIndexOfRecord2==null)?0:(sortIndexOfRecord1==null)?-1:1;
}
//Reframed the above logic like below. I got the same error
//Option 2: Throws same Timsort error:
/*
if(sortIndexOfRecord1!=null && sortIndexOfRecord2!=null){
if(sortIndexOfRecord1.intValue() == sortIndexOfRecord2.intValue())
return 0;
else if(sortIndexOfRecord1.intValue() < sortIndexOfRecord2.intValue())
return -1;
else if(sortIndexOfRecord1.intValue() > sortIndexOfRecord2.intValue())
return 1;
}else if(sortIndexOfRecord1==null && sortIndexOfRecord2==null){
return 0;
}else if(sortIndexOfRecord1==null && sortIndexOfRecord2!=null){
return -1;
}else if(sortIndexOfRecord1!=null && sortIndexOfRecord2==null){
return 1;
}
return 0;
*/
//Option 3: Throws same Timsort error:
/*
int index1 = -1;
int index2 = -1;
if(record1 != null && record2 != null){
index1 = indexToSortIndexMap.get(indexOfRecord1)!=null?indexToSortIndexMap.get(indexOfRecord1):-1 ;
index2 = indexToSortIndexMap.get(indexOfRecord2)!=null?indexToSortIndexMap.get(indexOfRecord2):-1 ;
}else if(record1 != null && record2 == null){
index1 = indexToSortIndexMap.get(indexOfRecord1)!=null?indexToSortIndexMap.get(indexOfRecord1):-1 ;
}else if(record1 == null && record2 != null){
index2 = indexToSortIndexMap.get(indexOfRecord2)!=null?indexToSortIndexMap.get(indexOfRecord2):-1 ;
}else{
index1 = -1;
index2 = -1;
}
if (index1 > index2){
return +1;
}else if (index1 < index2){
return -1;
}else{
return 0;
}
*/
以上所有产生以下错误:
Caused by: java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.TimSort.mergeLo(Unknown Source)
at java.util.TimSort.mergeAt(Unknown Source)
at java.util.TimSort.mergeCollapse(Unknown Source)
at java.util.TimSort.sort(Unknown Source)
答案 0 :(得分:0)
这三个选项似乎没问题。但是,您可以尝试使用标准比较器替换它们以确保:
return Comparator.nullsFirst(Integer::compare)
.compare(sortIndexOfRecord1, sortIndexOfRecord2);
一个可能的答案是,您实际上正在排序用于获取记录索引的records
列表。这是一个非常糟糕的主意。