KDj*_*ava 0 java sorting exception comparator
我无法使用我自己的Comparator实现通过Collections.sort()对我的集合进行排序.抛出的异常是 - >"IllegalArgumentException:比较方法违反了它的一般契约!在我的OrdersBean中,我已经覆盖了hashCode,如下所示:
@Override
public int hashCode() {
return this.getServiceOrderName().toUpperCase().hashCode();
}
Run Code Online (Sandbox Code Playgroud)
我没有过度使用equals()并仅使用Object类(不应该是我觉得的问题).
我已经将比较器实现为:
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;
}
}
};
Run Code Online (Sandbox Code Playgroud)
请建议我,我哪里出错了???
我现在改变了代码,如下所示,它对sort()方法运行正常,但现在最终在后面的代码中导致错误,此比较器被传递给树集,其中不允许重复,因此所有在比较器返回0的类似平台类型的情况下,这些命令不会添加到此sortedSet;(因为不允许重复):
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;
}
};
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
这表示<b AND b <a没有意义.
归档时间: |
|
查看次数: |
820 次 |
最近记录: |