Search code examples
javacollectionscomparable

What does "Mutually Comparable" mean?


I read that :

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

I wrote the below code and it worked correctly. Can you please tell how class b and class c are mutually comparable and what is the meaning of being "mutually comparable"?

import java.util.ArrayList;
import java.util.Collections;

class b implements Comparable<c> {
    String str1;

    b(String str1) {
        this.str1 = str1;
    }

    public int compareTo(c object) {
        return str1.compareTo(object.str1);
    }
}

class c implements Comparable<b> {
    String str1;

    c(String str1) {
        this.str1 = str1;
    }

    public int compareTo(b object) {
        return str1.compareTo(object.str1);
    }
}

public class a {

    public static void main(String[] args) {
        b obj1 = new b("monster");
        c obj2 = new c("aman");

        ArrayList list  = new ArrayList();
        list.add(obj1);
        list.add(obj2);
        System.out.println("unsorted list = "+list);
        Collections.sort(list);
        System.out.println("sorted list = "+list);
    }
}

Solution

  • 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.