A few years back, I wrote a post about how to use the Comparable and Comparator interfaces for comparing objects, “Two, If By Comparison“. While I was bringing the post over to this new site, I realized that it was written in the age long ago before Java generics. I decided to do a quick update to show how adding generics makes is a little easier.

Our first update will be the Comparable version of the Person class:

1
2
3
4
5
6
7
8
9
10
11
public class Person implements Comparable<Person> {
    private String id, firstName, lastName;
    private int age;

    // not showing all the getters and setters here...

    public int compareTo(Person person){
            // compare the last names using their compareTo methods
            return(lastName.compareTo(person.getLastName()));
    }
}

Note the Person parameter in the Comparable interface and the Person parameter in the compareTo() method. It gets rid of a few lines and makes the code a little more clear.

The Comparators become a bit more straight-forward as well:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class LastNameComparator implements Comparator<Person> {

    public boolean equals(Object obj){
            // we're just going to say that any LastNameComparators are equal
            return(obj instanceof LastNameComparator);
    }

    public int compare(Person p1, Person p2){
            // compare their lastNames
            return(p1.getLastName().compareTo(p2.getLastName()));
    }
}

public class AgeComparator implements Comparator<Person> {

    public boolean equals(Object obj){
            // we're just going to say that any AgeComparators are equal
            return(obj instanceof AgeComparator);
    }

    public int compare(Person p1, Person p2){
            // compare their ages
            int result = 0; // defaults to equal
            if(p1.getAge() > p2.getAge()){
                    result = 1;
            } else if(p1.getAge() < p2.getAge()){
                    result = -1;
            }

            return(result);
    }
}

Okay, so it’s nothing really astounding or Earth-shattering, but I felt the need to give a little update.

Popularity: 2% [?]

  • Share/Bookmark

Tags: , ,