android java.lang.IllegalArgumentException: Comparison method violates its general contract! 问题

 

android  java.lang.IllegalArgumentException: Comparison method violates its general contract! 问题

 

java.lang.IllegalArgumentException: Comparison method violates its general contract!
    at java.util.TimSort.mergeLo(TimSort.java:743)
    at java.util.TimSort.mergeAt(TimSort.java:479)
    at java.util.TimSort.mergeCollapse(TimSort.java:406)
    at java.util.TimSort.sort(TimSort.java:210)
    at java.util.TimSort.sort(TimSort.java:169)
    at java.util.Arrays.sort(Arrays.java:2038)
    at java.util.Collections.sort(Collections.java:1891)

 

 

 

需求排序:数据列表中如果fileName的文件存在的话,放到列表的最上面

 

public class MyData{

        private String fileName;

        public void setfileName(String fileName){
        this.fileName=fileName;
        }

        public String getfileName(){
        return this.fileName;
        }

        }
    
    private void MySort(List<MyData> MyDatas){ 

        Collections.sort(MyDatas, new Comparator<MyData>() {
                    @Override
                    public int compare(MyData lhs, MyData rhs) { // lhs和rhs 都要用上,不然会出错,本人测试是这样的,具体不知为何
                        // TODO Auto-generated method stub
                        if (lhs == null || rhs == null)
                            return 0;
                        String path="/mnt/file/";
                        // file one
                        String name1= lhs.getfileName();
                        String filename1 = path + name1; 
                        File file1 = new File(filename1);

                        // file two
                        String name2= rhs.getfileName();
                        String filename2 = path + name2; 
                        File file2 = new File(filename2);
                        
                        if (file1.exists() == true && file2.exists() == true) {
                            return 0;
                        } else {
                            if (file1.exists() == true) {
                                return 1;
                            } else {
                                return -1;
                            }
                        }
                    }
                });
                Collections.reverse(MyDatas);
    }

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。