Comparator and Comparable Interfaces. Java

0

My question is: Is it strictly necessary that when using Comparable we implement the interface on the class itself in which we want to establish the comparison and sort criteria for when we invoke sort () using compareTo ()?

Or could I create another class in which I pass the parameters and it returns what interests me in order? Ask the other way around for Comparator, since the examples they have given me follow that pattern and when I try to do it the other way around it does not seem to work and it has something in me that maybe I'll miss something.

    
asked by Sergio Gutiérrez 02.02.2018 в 18:08
source

1 answer

4

If you try to sort a list by the methods of the utils Collections class as follows Collections.sort(list) and the class of the list objects do not implement the interface Comparable , 2 things can happen:

  • Does not compile, if the list is typed and the type does not implement the interface Comparable .
  • A ClassCastException exception is thrown at runtime.

That's why you should implement Comparable as natural ordering or default of objects.

If you want to sort the list by another sorting criterion different from natural ordering, you must implement the Comparator interface and sort as Collections.sort(list, comparator) .

For this reason if you want to sort a list with the utils Collections.sort class you must implement one of the two interfaces Comparable for the case Collections.sort (list) or Comparator for the case Collections.sort (list, comparator)

You can find more information in the documentation at Java Ordering

    
answered by 02.02.2018 / 19:36
source