Comparable
Comparable
obj is the object to be compared. This method returns zero if the objects are equal.
It returns a positive value if current object is greater than obj. Otherwise, a negative
value is returned.
By overriding compareTo(), you can alter the way that objects are ordered. For
example, to sort in a reverse order, you can implement a comparison method that
reverses the outcome of a comparison.
The equals() method, shown here, tests whether an object equals the invoking
comparator −
obj is the object to be tested for equality. The method returns true if obj and the
invoking object are both Comparator objects and use the same ordering. Otherwise,
it returns false.
Overriding equals() is unnecessary, and most simple comparators will not do so.
Comparable Interface to Sort Custom Object
In this example, we're using Comparable interface to sort a custom object Dog based
on comparison criterias.
Example
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
Dog(String n, int a) {
name = n;
age = a;
}
@Override
public String toString() {
return this.name + "," + this.age;
}
}
public class ComparableDemo {
Output
Sorted by name:
[Lacy,2, Roger,10, Shaggy,3, Tammy,1, Tommy,4]
Example
Dog(String n, int a) {
name = n;
age = a;
}
@Override
public String toString() {
return this.name + "," + this.age;
}
}
Output
Example
In this example, we're using Comparable interface to sort Dog objects based on their
ages.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
Dog(String n, int a) {
name = n;
age = a;
}
@Override
public String toString() {
return this.name + "," + this.age;
}
}
Output
Sorted by age:
[Tammy,1, Lacy,2, Shaggy,3, Tommy,4, Roger,10]