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);
}
}