我使用简单的比较器并获得异常但不知道该怎么做
这就是我打电话的方式:
try {
Collections.sort(this.closePositions, new PositionComperator());
}
catch(Exception e) {
e.printStackTrace();
}
这是比较器:
public class PositionComperator implements Comparator<DataResponse> {
@Override
public int compare( DataResponse pos1, DataResponse pos2) {
if (pos1.openTime >= pos2.openTime) {
return 1;
}
else {
return -1;
}// returning 0 would merge keys
}
}
这是例外:
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)
at java.util.TimSort.sort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at java.util.Collections.sort(Unknown Source)
at GTTask.RefreshIdentityHistory.call(RefreshIdentityHistory.java:59)
at GTTask.RefreshIdentityHistory.call(RefreshIdentityHistory.java:1)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
答案 0 :(得分:2)
如果两个值x
和y
具有相同的openTime
,则compare(x, y)
和compare(y, x)
都将返回1,这违反了{{{0}的合同3}}:
实施者必须确保所有
sgn(compare(x, y)) == -sgn(compare(y, x))
和x
都y
。
你还没确定。
当openTime
值相同时,您需要考虑要发生的事情 - 返回0,或者某些一致的概念,哪个值应该先于另一个。例如,您是否可以进行二次比较?
答案 1 :(得分:1)
你可以使用treeSet。它适合你。并且有比较方法。例如
TreeSet<Double> sortedSet = new TreeSet<Double>();
比较它
TreeSet<Double> set = new TreeSet<Rock>(new Comparator<Double>()
public int compare(Double a, Double b){
return a.value - b.value;
}
}
答案 2 :(得分:1)
您收到此错误的原因是,当它对两个项目进行排序时,它们会更改顺序。您还应该包括它相等的情况。
最好是:
return po1.openTime - pos2.opentime;
或者做
if (pos1.openTime > pos2.openTime) {
return 1;
}
else if (pos1.openTime < pos2.openTime) {
return -1;
} else {
return 0;
}