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);}}}