Comparing Objects in Java

Mon, Jan 23, 2023 One-minute read

The object class needs to implement the Comparable interface to be able to be compared and you need to write a custom compareTo() method inside so it knows which fields to compare on implements Comparable<type to compare>

Here’s about the minimum code you need to implement.

You should write custom hashCode() and ?? methods too.

//CompareExample.java - just put all this into one file if you want

class Patient implements Comparable<Patient> {
    String name;

    public Patient(String name) {
        this.name = name;
    }

    public int compareTo(Patient other) {
        return this.name.compareTo(other.name);
    }
}

class CompareExample {
    public static void main(String[] args) {
        Patient andy = new Patient("Andy");
        Patient bob = new Patient("Bob");
        Patient charlie = new Patient("Charlie");

        System.out.println(andy.compareTo(bob)); // -1
        System.out.println(andy.compareTo(charlie)); //-2
    }
}