简体   繁体   中英

Exception when sorting array

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?

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..

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM