I keep getting: Comparison method violates its general contract! Exception for the below compare function when I call Arrays.sort(ScreenItems)
One assumption I have is that the ParseInt below is throwing an exception for the left object but not to the right object
Could that be the case?
public int compare(Object o1, Object o2) {
if (o2 == null || o1 == null)
return 0;
if (!(o1 instanceof ScreenItem) || !(o2 instanceof ScreenItem))
return 0;
ScreenItem item1 = (ScreenItem) o1;
ScreenItem item2 = (ScreenItem) o2;
String subSystem1 = item1.getSubSystem();
String subSystem2 = item2.getSubSystem();
if(subSystem1.equals(subSystem2)) {
return 0;
} else if(subSystem1.startsWith(subSystem2)) {
return 1;
} else if (subSystem2.startsWith(subSystem1)) {
return -1;
}
String order1 = item1.getOrder();
String order2 = item2.getOrder();
if (order1 == null || order2 == null){
String name1 = item1.getName();
String name2 = item2.getName();
if(name1 == null || name2 == null)
return 0;
return name1.compareToIgnoreCase(name2);
}
try {
return Integer.parseInt(order1) - Integer.parseInt(order2);
} catch (Exception ex) {
return 0;
}
}