-1

I have an array of Files that I am trying to sort by last modified date:

Arrays.sort(myFiles, new Comparator<File>(){
    public int compare(File f1, File f2) {
        return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
    }
});

I dont see any issues with this sort. lastModified should return a 0 if the file does not exist. However, sometimes I am getting the following exception:

java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.TimSort.mergeHi(TimSort.java:864)
at java.util.TimSort.mergeAt(TimSort.java:481)
at java.util.TimSort.mergeForceCollapse(TimSort.java:422)
at java.util.TimSort.sort(TimSort.java:219)
at java.util.TimSort.sort(TimSort.java:169)
at java.util.Arrays.sort(Arrays.java:2038)
at com.myapp.MyManager.getFiles(MyManager.java:101)
at com.myapp.MyManager$2.run(MyManager.java:171)
at java.lang.Thread.run(Thread.java:856)

Any ideas why this is happening?

Nick
  • 6,375
  • 5
  • 36
  • 53
  • 2
    possible duplicate of ["Comparison method violates its general contract!"](http://stackoverflow.com/questions/8327514/comparison-method-violates-its-general-contract) – kosa Oct 10 '12 at 19:10
  • @Nambari this is not a duplicate of that question, the other question dealt with parent class. As you can see, this question is a completely different case but with the same exception. – Nick Oct 10 '12 at 19:17

2 Answers2

4
public int compare(File f1, File f2) {
    return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
}

You forgot Long.valueOf on second operand..

public int compare(File f1, File f2) {
    return Long.valueOf(f1.lastModified()).compareTo(
           Long.valueOf(f2.lastModified()));
}

This might be giving you problem..

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
2

My guess is you are "modifying" the files (or at least updating the last modified time) during the sort. This means that the sorter is seeing something like A < B, B < C, and C < A, at which point it dies because it thinks your compare function must be broken.

Are you sorting files which are being modified by another process? It's also possible that viewing the modified time is updating the modified time, which will obviously break this sort.

Cory Kendall
  • 7,195
  • 8
  • 37
  • 64
  • Hmmm...thats a good point. I'll have to double check to make sure that's not happening... – Nick Oct 10 '12 at 19:27