Comparable vs Comparator
Students generally get confused with interfaces of Comparable and Comparator. In this article i am going to discuss about these two in detail. Collections do not have self sorting methods. So that they need to depend on Collections.sort() method. But this sort method can work only with the classes which has implemented Comparable interface or Comparator interface only. Otherwise it leads to Compile time error. Consider the following program. import java.util.ArrayList; import java.util.Collections; import java.util.List; class S { int sno; S(int sno) { this.sno=sno; } @Override public int compareTo(S o) { if(sno==o.sno) { return 0; } else if(sno>o.sno) { return 1; } else return -1; } } public class Test2 { public static void main(String[] args) { ArrayList<S> a=new ArrayList<>(); a.add(new S(20)); a.add(new S(30)); a.add(new S(10)); Collections.sort(a); for(S x:a) { System.out.println(x.sn...





Comments
Post a Comment