轉(zhuǎn)載自:http://blog.csdn.net/fanzitao/article/details/8040201
Brother Zeng遇到的錯(cuò)誤:
Java.lang.IllegalArgumentException: Comparison method violates its general contract!
網(wǎng)上查到一個(gè)解釋?zhuān)?br>
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.
也就是說(shuō)jdk 7的sort函數(shù)的實(shí)現(xiàn)變了爪瓜,造成了這個(gè)問(wèn)題,具體原因未知然评。
改一下系統(tǒng)設(shè)置,還是選擇使用老版本的排序方法叶摄,在代碼前面加上這么一句話(huà):System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");
另外復(fù)習(xí)一下比較器属韧,一個(gè)簡(jiǎn)單的例子:
類(lèi)代碼:
public class Stu {
public double age;
public String name;
public Stu(String name,double age)
{
this.name = name;
this.age = age;
}
}
測(cè)試
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有可能報(bào)錯(cuò)蛤吓,
//加上這句話(huà):System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");
//表示宵喂,使用以前版本的sort來(lái)排序
Collections.sort(list,comparator);
for(int i=0;i<list.size();i++)
{
System.out.println(list.get(i).age+" "+list.get(i).name);
}
}
}