What does “Mutually Comparable” mean?

后端 未结 4 890
慢半拍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:53

    In order for classes A and B to be mutually comparable, these requirements need to be satisfied:

    • A call of compareTo on an instance of A passing an instance of B must be allowed
    • A call of compareTo on an instance of B passing an instance of A must be allowed
    • If a.compareTo(b) returns x, then b.compareTo(a) must return a value y with the opposite sign, or zero, when x is zero.

    The classes in your code are not mutually comparable, because an attempt to pass an instance of c to b's compareTo (and vice versa) works fine. However, they are not comparable to instances of their own classes, which would create a problem if you were to add more items to the collection to be sorted.

    In order for the container to be sortable, your class needs to be comparable to instances of its own type as well.

提交回复
热议问题