I am having trouble to sort my collection by Collections.sort() using my own Comparator implementation.
The exception thrown is–>”IllegalArgumentException: Comparison method violates its general contract!
In my OrdersBean I have over-ridden the hashCode as this:
@Override
public int hashCode() {
return this.getServiceOrderName().toUpperCase().hashCode();
}
I have not over-ridden equals() and using that of the Object class only(should not be a problem I feel).
And I have implemented the comparator as this:
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;
}
}
};
Please suggest me , where I am going wrong???
I have changed the code now as follows, Its running fine for sort() method but it is now eventually causing an error in a later code where this comparator is passed to the Tree-Set, where duplicates are not allowed, and thus all the cases of similar platform types where the comparator return 0 , those orders are not added to this sortedSet;(as duplicates are not allowed):
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)must be the same as-compare(b, a)otherwise there is no deterministic way to compare a and b. You haveThis says a < b AND b < a which makes no sense.