Reputation: 834
I think below implementation of a comprator is wrong. It will got give me a sorted order of Strings. But when i use this implementation to sort a List it does not throw the below exception : "java.lang.IllegalArgumentException: Comparison method violates its general contract!"
Question : Why above Exception is not thrown by Collections.sort(list, new WrongComparator()) method call ?
public class WrongComparator implements Comparator<String> {
public int compare(String o1, String o2){
return 1;
}
}
Upvotes: 2
Views: 281
Reputation: 4869
Because IllegalArgumentException is thrown if it's detected. It means, that Collections.sort(..) doesn't make special checks on comparator, but if something goes wrong during the sorting (because of a bad comparator), this exception is thrown. Collections.sort() use Tim sort algorithm and comparator check is performed at the end of the merge phase.
Why don't you get this exception in this particular case?
Because your collection is already sorted, according to you comparator. Tim's algorithm detects that it's already sorted and doesnt' perform any merge.
Upvotes: 1