1.

What Is Comparable And Comparator Interface?

Answer»

In java. all collection which have feature of AUTOMATIC sorting, uses compare METHODS to ensure the correct sorting of elements. For example classes which use sorting are TreeSet, TreeMap etc.

To sort the data elements a class NEEDS to implement Comparator or Comparable interface. That’s why all Wrapper classes like Integer,Double and String class implements Comparable interface.

Comparable helps in PRESERVING default natural sorting, whereas Comparator helps in sorting the elements in some special required sorting pattern. The instance of comparator if passed usually as collection’s constructor argument in SUPPORTING collections.

In java. all collection which have feature of automatic sorting, uses compare methods to ensure the correct sorting of elements. For example classes which use sorting are TreeSet, TreeMap etc.

To sort the data elements a class needs to implement Comparator or Comparable interface. That’s why all Wrapper classes like Integer,Double and String class implements Comparable interface.

Comparable helps in preserving default natural sorting, whereas Comparator helps in sorting the elements in some special required sorting pattern. The instance of comparator if passed usually as collection’s constructor argument in supporting collections.



Discussion

No Comment Found