What does “Mutually Comparable” mean?

后端 未结 4 885
慢半拍i
慢半拍i 2021-01-07 07:19

I read that :

whenever a collection need to be sorted, the elements must be mutually comparable.

I wrote the below code and it

4条回答
  •  春和景丽
    2021-01-07 07:52

    Mutually comparable means that instances of both classes must be comparable to the other.

    In case of type A and type B:

    • A must implement Comparable where T extends B (or is B)
    • B must implement Comparable where U extends A (or is A)
    • The comparison must be consistent. Consistent means that if a>b then it must be so b. And if a then it must be so b>a. And if a==b then it must be so b==a.

    So that the following code can be written:

    A a = ...;
    B b = ...;
    
    int rab = a.compareTo(b);  // A is comparable to B
    int rba = b.compareTo(a);  // B is comparable to A
    
    // And also consistent:
    if (   !(rab<0 && rba>0)
        || !(rab>0 && rba<0)
        || !(rab==0 && rba!=0))
        System.out.println("Not consistent!");
    

    If type A and type B are the same, then a and b are obviously mutually comparable.

    Sorting algorithms usually require the elements to be mutually comparable so they can compare any 2 of the sortable elements to each other.

    Back to your question

    Your case is special. Your 2 objects obj1 and obj2 are mutually comparable according to the definition. Your obj1 and obj2 instances are mutually comparable, but your b and c classes are not.

    However, if you would pass another instance of either type a or type b, all elements would be not. Because if we would select 2 instances from the collection of the same type, they would not implement Comparable to the same type.

    obj1.compareTo(obj2); // This is valid, b implements Comparable
    obj2.compareTo(obj1); // This is also valid, c implements Comparable
    
    obj1.compareTo(obj1); // This is NOT valid! b does not implement Comparable
    

提交回复
热议问题