比較子報錯:Comparison method violates its general contract

來源:互聯網
上載者:User

Brother Zeng遇到的錯誤:

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

網上查到一個解釋:

Description: The sorting algorithm used by java.util.Arrays.sort and (indirectly) by java.util.Collections.sort has been replaced. The new sort implementation may throw an IllegalArgumentException if it detects a Comparable that violates the Comparable contract.
The previous implementation silently ignored such a situation. If the previous behavior is desired, you can use the new system property, java.util.Arrays.useLegacyMergeSort, to restore previous mergesort behavior.

也就是說jdk 7的sort函數的實現變了,造成了這個問題,具體原因未知。

改一下系統設定,還是選擇使用老版本的排序方法,在代碼前面加上這麼一句話:System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");

另外複習一下比較子,一個簡單的例子:

類代碼:

public class Stu {public double age;public String name;public Stu(String name,double age){this.name = name;this.age = age;}}

主題代碼

import java.util.Collections;import java.util.Comparator;import java.util.List;public class CodeForBrotherZeng {/** * @param args */public static void main(String[] args) {Stu stu1=new Stu("foyd",22.1);Stu stu2=new Stu("teddy",19.1);Stu stu3=new Stu("dean",26.1);Stu stu4=new Stu("lucas",19.1);Stu stu5=new Stu("tina",26.1);List<Stu> list = new ArrayList<Stu>();list.add(stu1);list.add(stu2);list.add(stu3);list.add(stu4);list.add(stu5);Comparator<Stu> comparator = new Comparator<Stu>() {public int compare(Stu p1, Stu p2) {//return必須是int,而str.age是double,所以不能直接return (p1.age-p2.age)if((p1.age-p2.age)<0) return -1;else if((p1.age-p2.age)>0)return 1;else return 0;}};//jdk 7sort有可能報錯,//加上這句話:System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");//表示,使用以前版本的sort來排序Collections.sort(list,comparator);for(int i=0;i<list.size();i++){System.out.println(list.get(i).age+"  "+list.get(i).name);}}}

  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.