我在使用我自己的比较器实现通过 Collections.sort() 对我的集合进行排序时遇到问题。 抛出的异常是-->“IllegalArgumentException:比较方法违反了其一般契约! 在我的 OrdersBean 中,我已经重写了 hashCode,如下所示:
@Override
public int hashCode() {
return this.getServiceOrderName().toUpperCase().hashCode();
}
我没有重写 equals() 并仅使用 Object 类的 equals() (我觉得这不应该是一个问题)。
我已经实现了比较器,如下所示:
public static final Comparator<OrdersBean> ordersComparator=new Comparator<OrdersBean>() {
@Override
public int compare(OrdersBean first, OrdersBean second)
{
if(Double.parseDouble(first.getPriority())<Double.parseDouble(second.getPriority()))
return -1;
else
if(Double.parseDouble(first.getPriority())>Double.parseDouble(second.getPriority()))
return +1;
else
{
if((first.getPlatformType().equalsIgnoreCase("EV-DO Carrier ADD")) &&
(second.getPlatformType().equalsIgnoreCase("EV-DO Carrier ADD")))
return -1;
if((first.getPlatformType().equalsIgnoreCase("T1 Augment")) &&
(second.getPlatformType().equalsIgnoreCase("T1 Augment")))
return -1;
if(first.getPlatformType().equalsIgnoreCase("EV-DO Carrier ADD"))
return -1;
else
if(second.getPlatformType().equalsIgnoreCase("EV-DO Carrier ADD"))
return +1;
else
if(first.getPlatformType().equalsIgnoreCase("T1 Augment"))
return -1;
else
if(second.getPlatformType().equalsIgnoreCase("T1 Augment"))
return +1;
else
return -1;
}
}
};
请建议我,我哪里出错了???
我现在已经更改了代码,如下所示,它对于 sort() 方法运行良好,但现在最终会在稍后的代码中导致错误,其中该比较器被传递到不允许重复的树集,并且因此,在比较器返回 0 的类似平台类型的所有情况下,这些订单都不会添加到此排序集中;(因为不允许重复):
public static final Comparator<OrdersBean> ordersComparator=new Comparator<OrdersBean>() {
@Override
public int compare(OrdersBean first, OrdersBean second)
{
int diffProrties=(int)(Double.parseDouble(first.getPriority())-Double.parseDouble(second.getPriority()));
if(diffProrties != 0)
return diffProrties;
if(first.getPlatformType().equalsIgnoreCase(second.getPlatformType()))
return 0;
if(first.getPlatformType().equalsIgnoreCase("EV-DO Carrier ADD"))
return -1;
if(second.getPlatformType().equalsIgnoreCase("EV-DO Carrier ADD"))
return +1;
if(first.getPlatformType().equalsIgnoreCase("T1 Augment"))
return -1;
if(second.getPlatformType().equalsIgnoreCase("T1 Augment"))
return +1;
return 0;
}
};
最佳答案
compare(a,b)
必须与 -compare(b, a)
相同,否则无法确定比较 a 和 b 的方法。你有
if((first.getPlatformType().equalsIgnoreCase("EV-DO Carrier ADD")) &&
(second.getPlatformType().equalsIgnoreCase("EV-DO Carrier ADD")))
return -1;
这表示 a < b AND b < a,这没有任何意义。
关于java 7 中的 Java 排序(TimSort-MergeSort): Dangerous,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11586217/