简体   繁体   English

排序数组时发生异常

[英]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. 如果文件不存在,lastModified应该返回0。 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.. 您忘记了第二个操作数上的Long.valueOf

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. 这意味着排序器看到A < BB < CC < A ,此时它死了,因为它认为您的compare功能必须中断。

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. 查看修改时间也可能会更新修改时间,这显然会破坏这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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