我使用简单的comperator,得到异常,不知道该怎么做
我就是这样称呼的:
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)发布于 2013-07-31 08:16:03
出现此错误的原因是,当对两个项进行排序时,它们更改了顺序。你也应该包括它是相等的情况。
最好做:
return po1.openTime - pos2.opentime;或者做
if (pos1.openTime > pos2.openTime) {
return 1;
}
else if (pos1.openTime < pos2.openTime) {
return -1;
} else {
return 0;
}发布于 2013-07-31 08:13:45
如果两个值x和y具有相同的openTime,那么compare(x, y)和compare(y, x)都将返回1,这违反了compare的契约。
实现者必须确保
sgn(compare(x, y)) == -sgn(compare(y, x))适用于所有x和y。
你还没保证。
当openTime值相同时,您需要考虑想要发生什么--或者返回0,或者有一些一致的概念,说明哪个值应该放在另一个值之前。例如,您是否可以进行一些次要的比较?
发布于 2013-07-31 08:14:33
您可以使用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;
}
}https://stackoverflow.com/questions/17964963
复制相似问题