Comparable

This interface imposes a total ordering on the objects of each class that implements it.

int compareTo(T o) Compares this object with the specified object for order.

This method compares the invoking object with obj.

  • It returns 0 if the values are equal.
  • It returns a negative value if the invoking object has a lower value.
  • Otherwise, a positive value is returned.

The Byte, Character, Double, Float, Long, Short, String, and Integer classes define a compareTo( ) method.

The following example create a class Person which implements the Comparable interface. Person array is created and passed into TreeSet. The TreeSet sorts the person array and then output.


import java.util.Arrays;
import java.util.Set;
import java.util.TreeSet;

public class Main {
  public static void main(String[] argv) {
    Person emps[] = { new Person("A", "B"), new Person("C", "D"), new Person("E", "F"),
        new Person("G", "H"), new Person("I", "J") };
    Set set = new TreeSet(Arrays.asList(emps));
    System.out.println(set);
  }
}

class Person implements Comparable {
  String firstName, lastName;

  public Person(String f, String l) {
    this.firstName = f;
    this.lastName = l;
  }

  public String getFirstName() {
    return firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public String toString() {
    return firstName + ",name=" + lastName;
  }

  public int compareTo(Object obj) {
    Person emp = (Person) obj;
    int deptComp = firstName.compareTo(emp.getFirstName());

    return ((deptComp == 0) ? lastName.compareTo(emp.getLastName()) : deptComp);
  }

  public boolean equals(Object obj) {
    if (!(obj instanceof Person)) {
      return false;
    }
    Person emp = (Person) obj;
    return firstName.equals(emp.getFirstName()) && lastName.equals(emp.getLastName());
  }
}
  

The output:


[A,name=B, C,name=D, E,name=F, G,name=H, I,name=J]
Home 
  Java Book 
    Collection