2012-12-07 46 views
4

java7是否存在排序問題?我使用Collections.sort(名單時,比較器)java7中的Collections.sort()問題

當我切換到java7,我注意到,分揀導致了不同的列表相比,當我使用的Java6的結果。

實施例:列表= [d,E,B,A,C,F,G,H]

在的Java6 Collections.sort(列表,比較器)導致[A,B,C,d, E,F,G,H]

在java7 Collections.sort(列表,比較器)導致並[b,A,C,d,E,F,G,H]

中的前兩個值該列表已被交換。

+1

孤單只是沒有辦法的人 – thatidiotguy

+0

報告到Oracle的錯誤.. – Smit

+3

似乎是不可能的Collections.sort壞了。什麼是你觀察到這個結果的實際數據(如圖所示的字符或字符串數​​組)?你是否將比較器傳遞給它? – femtoRgon

回答

8

Java 7的切換,從Merge sortTim sort。這可能導致爲了與「破比較」(引述的Arrays class源代碼註釋)的微小變化:

/** 
* Old merge sort implementation can be selected (for 
* compatibility with broken comparators) using a system property. 
* Cannot be a static boolean in the enclosing class due to 
* circular dependencies. To be removed in a future release. 
*/ 

嘗試與運行的JVM:

java -Djava.util.Arrays.useLegacyMergeSort=true 

目前還不清楚是什麼「 破碎比較器「的意思,但顯然它可能會導致排序陣列中元素的順序不同。

0

有一點要注意,這可能會導致混淆。 Collections.sort是一個穩定的排序。這意味着相等的元素,它保持原來的排序,所以:

如果== b,則

Collections.sort([d, e, b, a, c, f, g, h]) = [b, a, c, d, e, f, g, h] 

Collections.sort([d, e, a, b, c, f, g, h]) = [a, b, c, d, e, f, g, h] 

似乎有可能我說,要麼就是你看到問題的Comparator(或正在排序的對象的自然順序)不能按照您期望的方式工作。