The Comparator interface defines two methods: compare() and equals() .
The compare() method compares two elements in order: int compare(Object obj1, Object obj2)
obj1 and obj2 are objects to compare. This method returns zero if the objects are equal. Returns a positive value if obj1 is greater than obj2. Otherwise, a negative value is returned.
By compare() , you can reorder the objects. For example, to sort in the reverse order, you can create a comparator that flips the comparison results.
The equals() method checks to see if the object is equal to the calling comparator: boolean equals(Object obj)
obj is an object that needs to be checked for equality. The method returns true if obj and the caller are Comparator objects and use the same order. Otherwise, false is returned.
Example:
import java.util.*; class Dog implements Comparator<Dog>, Comparable<Dog> { private String name; private int age; Dog() { } Dog(String n, int a) { name = n; age = a; } public String getDogName() { return name; } public int getDogAge() { return age; }
Check out other Java Comparator examples .
source share