Reputation: 2365
I am having some problems sorting an array of files on a Java 7 virtual machine. Sometimes I get IllegalArgumentException from TimSort complaining about "Comparison method violates its general contract!". The comparator is relatively simple:
final File[] filesList = importDirectory.listFiles();
Arrays.sort(filesList, new Comparator<File>() {
public int compare(File f1, File f2) {
return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
}
});
What's wrong with this implementation? And why doesn't it fail on a Java 6 VM (I have read, that the TimSort Algorithm used in Java 7 is more restrictive, than the normal Merge sort of Java 6, but I still can't see where I'm violating the comparator contract.
Chris
Upvotes: 0
Views: 407
Reputation: 533620
This would break of one of the files is modified when you are sorting it.
One way to make this faster (as lastModified is expensive) and avoid this issue is to build a Map of modification dates.
Map<File, Long> lastModifiedMap =
Upvotes: 2