I have googled and checked thoroughly all the questions and answers of "Comparison method violates its general contract" error. I am not able to figure out in scenario what is going wrong. I have written a comparator class which sometime throws this exception in CI. I am only using Integer obj.compareTo method in my NumberStringComparator and this class is used in Arrays.sort method.
Arrays.sort(valuesArray, new NumberStringComparator());
Class code
private static class NumberStringComparator implements Comparator<Object>
{
@Override
public int compare (Object entry1, Object entry2) {
if(!(entry1 instanceof String && entry2 instanceof String)){
throw new ClassCastException();
}
try{
Integer a1 = Integer.valueOf((String)entry1);
Integer a2 = Integer.valueOf((String)entry2);
return a1.compareTo(a2);
}
catch(Exception e){
try{
return ((String)entry1).compareTo((String)entry2);
}
catch(Exception e1){
throw new ClassCastException();
}
}
}
}
edited: sample values (more than thousand values) used are :
1234567894, 1234567893, 1234567892, 1234567891, 1234567890, 12345678949, 491940032, 491940033, 12345678947, 491940030, 12345678948