[JAVA] Comparable and Comparator (ordering objects)

Very confusing

If you want to sort, you can use TreeSet instead of HashSet, but sometimes you want to give your own original ordering. In such a case, Comparator and Comparable are effective.

Comparable java.lang.Comparable interface "comparable" (1) The TreeSet class performs the process of casting to __Comparable type __ when rearranging the elements internally. (2) Value classes such as String class and Integer class of the standard library implement the Comparable interface.

Myclass.java


class MyClass implements Comparable<Myclass>{
  //Implementation of abstract methods
  public int compareTo(Myclass obj){
    return this.id - obj.id; 
  }
}
//ascending order

Comparator java.util.Comparator interface "Comparator" The motivation for using Comparator is when you want to change the sort order of elements stored in TreeSet, TreeMap, etc. to a different order from the default.

Myclass.java


class Myclass implements Comparator<String>{
  @Override 
  public int compare(String obj1, String obj2){
     return obj1.length() - obj2.length();
  }
}
//ascending order
constructor Description
TreeSet(Comparator<? super E> comparator) Creates a new empty tree set sorted according to the specified comparator

The TreeSet declares a constructor that takes a Comparator object as an argument (described in OraDocs), so any sort order can be applied.

Summary

Comparable "Compares You with Other Objects" Comparator "Compares Two Other Objects" (Note: The definitions of TreeSet and TreeMap may be vague rather than confusing for Comparable and Comparator)

Recommended Posts

Comparable and Comparator (ordering objects)
mutable and immutable objects
[Java8] Proper use of Comparable and Comparator in terms of employee sorting