Skip to content

Interfaces

Common Interfaces to Implement

Comparator

Compares two instances of a class.

java
class StudentGPAComparator implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        return (o1.gpa + o1.name).compareTo(o2.gpa + o2.name);
    }
}

public static void main() {
    Comparator<Student> gpaSorter = new StudentGPAComparator();
    Arrays.sort(students, gpaSorter);
    Arrays.sort(students, gpaSorter.reversed());
}

Comparable

Similar to Comparator, except this is implemented directly on the classes you are comparing. Without specificing a type, you will receive an Object to your compareTo function.

java
class Student implements Comparable<Student> {
    @Override
    public int compareTo(Student o) {
        return this.name.compareTo(o.name);
    }
}