我用簡單的comperator並獲得異常,不知道該怎麼辦Java集合排序問題
這是我如何打電話:
try {
Collections.sort(this.closePositions, new PositionComperator());
}
catch(Exception e) {
e.printStackTrace();
}
這是comperator:
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)
'sort'不能引起元素得到合併。雖然如果你要使用Set,那將是一個不同的故事。 – Dukeling
你可以提供PositionComperator的代碼 – Ruju