java集合排序问题

时间:2013-07-31 08:11:14

标签: java collections compare

我使用简单的比较器并获得异常但不知道该怎么做

这就是我打电话的方式:

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)

3 个答案:

答案 0 :(得分:2)

如果两个值xy具有相同的openTime,则compare(x, y)compare(y, x)都将返回1,这违反了{{{0}的合同3}}:

  

实施者必须确保所有sgn(compare(x, y)) == -sgn(compare(y, x))xy

你还没确定。

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;
}
相关问题