我使用简单的比较器并得到异常,但不知道该怎么办
这就是我的称呼:
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
}
}
这是异常(exception):
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)
最佳答案
如果两个值x
和y
具有相同的openTime
,则compare(x, y)
和compare(y, x)
都会返回 1,这违反了 compare
的约定:
The implementor must ensure that
sgn(compare(x, y)) == -sgn(compare(y, x))
for allx
andy
.
你还没有确保这一点。
您需要考虑当 openTime
值相同时您想要发生什么 - 要么返回 0,要么对哪个值应该出现在其他。例如,您是否可以进行一些二次比较?
关于java集合排序问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17964963/