簡體   English   中英

Java中Collections.sort的內部

[英]Internals of Collections.sort in java

我試圖了解排序過程中列表中的元素何時交換。 到目前為止,我的理解是在比較期間,當我們返回-1或0時沒有交換發生,而當我們返回1交換時發生了。 下面是代碼

public class ArraySort {
    public static void main(String[] args) {
        Integer [] input = {1,10};
        List<Integer> inputList =Arrays.asList(input);
        Collections.sort(inputList,(a,b)->a>b?-1:1);
        System.out.println(inputList);
    }
}

返回[10,1] ----我理解這一點。 由於我們從比較中返回1,因此發生了交換。

public class ArraySort {
    public static void main(String[] args) {
        Integer [] input = {1,10};
        List<Integer> inputList =Arrays.asList(input);
        Collections.sort(inputList,(a,b)->a>b?1:-1);//changed the signs
        System.out.println(inputList);
    }
}

返回[1,10]-我理解這是因為從返回-1開始就沒有交換發生。

public class ArraySort {
    public static void main(String[] args) {
        Integer [] input = {1,10};
        List<Integer> inputList =Arrays.asList(input);
        Collections.sort(inputList,(a,b)->a>b?-1:-1); // both are negative.
        System.out.println(inputList);
    }
}

返回[10,1]-我不明白這是為什么發生交換,因為返回-1不會導致交換正確嗎? 請澄清我的誤會。

我再次嘗試在該論壇上發帖,但對我的問題可以得到滿意的答案。 比較器的返回類型

Comparatorjavadoc中

在前面的描述中,符號sgn(expression)表示數學符號函數,其被定義為返回一個-10 ,或1根據表達式的值是否為負,零或正。

實現者必須確保所有xy sgn(compare(x, y)) == -sgn(compare(y, x)) (這意味着,當且僅當compare(y, x)引發異常時, compare(x, y)必須引發異常。)

實現者還必須確保該關系是可傳遞的: ((compare(x, y)>0) && (compare(y, z)>0))意味着compare(x, z)>0

最后,實現者必須確保compare(x, y)==0意味着所有z sgn(compare(x, z))==sgn(compare(y, z))

您的實現打破了這些假設:當您始終返回-1 ,您至少打破了第一個假設:

sgn(compare(x, y)) == -sgn(compare(y, x))如果始終返回-1則不成立: sgn(compare(x, y)) == sgn(compare(y, x))對於所有xy

由於排序代碼依賴於您正確遵守此合同,因此這導致不確定的行為。

您沒有打破它。 您所做的是,無論Comparator什么,您都在告訴比較器,它始終低於可比較的值。 例如,如果您這樣使用它

 Integer[] input = {
     1, 6, 8, 2, 10
 };
 List < Integer > inputList = Arrays.asList(input);
 Collections.sort(inputList, (a, b) - > a > b ? -1 : -1); // both are negative.
 System.out.println(inputList);

它將打印[10, 2, 8, 6, 1] 因為它是從左到右比較開始的,所以它會還原列表。

Comparator實現不遵守Comparator.compare()的規范:

Collections.sort(inputList,(a,b)->a>b?-1:-1); // both are negative.

規范指出:

實現者必須確保> x和y都等於(compare(x,y))== -sgn(compare(y,x))。

在您的實現中,您沒有這個平等,但是有一個:

sgn(compare(x, y)) == sgn(compare(y,> x))

當Collection方法操縱您的對象時,不遵守該方法的約定可能會導致無法預測的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM