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
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.
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)