Comparable

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

ReturnMethodSummary
intcompareTo(T o)Compares this object with the specified object for order.

This method compares the invoking object with obj.

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]
java2s.com  |  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.