Making Java Objects Comparable

 
Making Java Objects Comparable
by Budi Kurniawan
03/12/2003
In real life, objects are often comparable. For example, Dad's car is more expensive than Mom's, this dictionary is thicker than those books, Granny is older than Auntie Mollie (well, yeah, living objects, too, are comparable), and so forth. In writing object-oriented programs, there are often needs to compare instances of the same class. And once instances are comparable, they can be sorted. As an example, given two Employees, you may want to know which one has stayed in the organization longer. Or, in a search method for Person instances with a first name of Larry, you may want to display search results sorted by age. This article teaches you how to design your class to make its instances comparable by using the java.lang.Comparable and java.util.Comparator interfaces and presents three examples that illustrate both interfaces.
Most Java programmers know how to sort the elements of a String array by using the sort method of java.util.Arrays. For String instances in an ArrayList, you can sort them with the sort method of the java.util.Collections class. The code in Listing 1 shows how to use Arrays.sort to order String instances.
import java.util.Arrays;
 
.
.
.
 
String animals[] = new String[4];
animals[0] = "snake";
animals[1] = "kangaroo";
animals[2] = "wombat";
animals[3] = "bird";
 
for (int i=0; i<4; i++) {
 System.out.println("animal " + i + " : " + animals[i]);
}
 
Arrays.sort(animals);
 
for (int i=0; i<4; i++) {
 System.out.println("animal " + i + " : " + animals[i]);
}
If you run the program, the first for loop gives you the name of animals as follows:
animal 0 : snake
animal 1 : kangaroo
animal 2 : wombat
animal 3 : bird
And, the second for loop prints the animals sorted alphabetically.
animal 0 : bird
animal 1 : kangaroo
animal 2 : snake
animal 3 : wombat
With the java.util.Collections class's sort method, you can sort String instances in an ArrayList, as shown in Listing 2.
import java.util.ArrayList;
import java.util.Collections;
 
.
.
.
 
ArrayList insects = new ArrayList();
insects.add("mosquito");
insects.add("butterfly");
insects.add("dragonfly");
insects.add("fly");
 
int size = insects.size();
for (int i=0; i<size; i++) {
 System.out.println("insect " + i + " : " + (String) insects.get(i));
}
 
Collections.sort(insects);
 
for (int i=0; i<size; i++) {
 System.out.println("insect " + i + " : " + (String) insects.get(i));
}
The first for loop in Listing 2 produces the following output:
insect 0 : mosquito
insect 1 : butterfly
insect 2 : dragonfly
insect 3 : fly
The second for loop prints the following:
insect 0 : butterfly
insect 1 : dragonfly
insect 2 : fly
insect 3 : mosquito
However, suppose we have a Person class, as in Listing 3.
class Person {
 private String firstName;
 private String lastName;
 private int age;
 
 public String getFirstName() {
    return firstName;
 }
 
 public void setFirstName(String firstName) {
    this.firstName = firstName;
 }
 
 public String getLastName() {
    return lastName;
 }
 
 public void setLastName(String lastName) {
   this.lastName = lastName;
 }
 
 public int getAge() {
    return age;
 }
 
 public void setAge(int age) {
    this.age = age;
 }
}
In another part of the program, we construct four instances of the Person class and populate them with names and ages:
  Person[] persons = new Person[4];
 persons[0] = new Person();
 persons[0].setFirstName("Elvis");
 persons[0].setLastName("Goodyear");
 persons[0].setAge(56);
 
 persons[1] = new Person();
 persons[1].setFirstName("Stanley");
 persons[1].setLastName("Clark");
 persons[1].setAge(8);
 
 persons[2] = new Person();
 persons[2].setFirstName("Jane");
 persons[2].setLastName("Graff");
 persons[2].setAge(16);
 
 persons[3] = new Person();
 persons[3].setFirstName("Nancy");
 persons[3].setLastName("Goodyear");
 persons[3].setAge(69);
How do we sort these Person instances by age or by name? Using the java.util.Arrays class' sort method, as in:
Arrays.sort(persons);
will throw a ClassCastException.
You can, of course, write your own code to sort them using an algorithm such as quick sort, bubble sort, or others, but that's impractical. The easy solution is to implement the java.lang.Comparable interface.
java.lang.Comparable Interface
Implement the Comparable interface to make class instances comparable. This interface has one method, compareTo, which determines how to compare two instances of the class. The signature of this method is:
public int compareTo(Object o)
The compareTo method accepts Object, so you can pass it an instance of any type. However, chances are that you want to make sure to compare two instances of the same type. It does not make sense to compare an elephant with an ant, for example. Therefore, you can throw a java.lang.ClassCastException if the argument of this method is not the same type as your class.
The compareTo method returns zero if the object passed is equal to this instance. It returns a positive integer or a negative integer if this object is greater or smaller than the passed object, respectively.
Let's have a look at the examples in Listing 4 and Listing 5. Listing 4 presents a Person class that implements the Comparable interface. Notice that a Person object is older if its age value is greater than the object compared. Listing 5 shows the Testing class that constructs four instances of the Person class and sorts them by age. Both classes in Listings 4 and 5 reside in the comparable.ex01 package.
package comparable.ex01;
 
class Person implements Comparable {
 private String firstName;
 private String lastName;
 private int age;
 
 public String getFirstName() {
    return firstName;
 }
 
 public void setFirstName(String firstName) {
    this.firstName = firstName;
 }
 
 public String getLastName() {
    return lastName;
 }
 
 public void setLastName(String lastName) {
    this.lastName = lastName;
 }
 
 public int getAge() {
    return age;
 }
 
 public void setAge(int age) {
    this.age = age;
 }
 
 public int compareTo(Object anotherPerson) throws ClassCastException {
    if (!(anotherPerson instanceof Person))
      throw new ClassCastException("A Person object expected.");
    int anotherPersonAge = ((Person) anotherPerson).getAge(); 
    return this.age - anotherPersonAge;   
 }
}
package comparable.ex01;
 
import java.util.Arrays;
import java.util.ArrayList;
 
public class Testing {
 
 public static void main(String[] args) {
    Person[] persons = new Person[4];
    persons[0] = new Person();
    persons[0].setFirstName("Elvis");
    persons[0].setLastName("Goodyear");
    persons[0].setAge(56);
 
    persons[1] = new Person();
    persons[1].setFirstName("Stanley");
    persons[1].setLastName("Clark");
    persons[1].setAge(8);
 
    persons[2] = new Person();
    persons[2].setFirstName("Jane");
    persons[2].setLastName("Graff");
    persons[2].setAge(16);
 
    persons[3] = new Person();
    persons[3].setFirstName("Nancy");
    persons[3].setLastName("Goodyear");
    persons[3].setAge(69);
 
    System.out.println("Natural Order");
 
    for (int i=0; i<4; i++) {
      Person person = persons[i];
      String lastName = person.getLastName();
      String firstName = person.getFirstName();
      int age = person.getAge();
      System.out.println(lastName + ", " + firstName + ". Age:" + age);
    }
 
    Arrays.sort(persons);
 
    System.out.println();
    System.out.println("Sorted by age");
 
    for (int i=0; i<4; i++) {
      Person person = persons[i];
      String lastName = person.getLastName();
      String firstName = person.getFirstName();
      int age = person.getAge();
      System.out.println(lastName + ", " + firstName + ". Age:" + age);
    }
 }
}
The result of the code in Listing 5 is as follows:
Natural Order
Goodyear, Elvis. Age:56
Clark, Stanley. Age:8
Graff, Jane. Age:16
Goodyear, Nancy. Age:69
 
Sorted by age
Clark, Stanley. Age:8
Graff, Jane. Age:16
Goodyear, Elvis. Age:56
Goodyear, Nancy. Age:69
java.util.Comparator Class
Implementing the Comparable interface enables you to define one way to compare instances of your class. However, objects are sometimes comparable in many ways. For example, two Person objects may need to be compared by age or by last/first name. In cases like this, create a Comparator that defines how to compare two objects. To make objects comparable in two ways, then you need two comparators.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值