Comparable

In this chapter you will learn:

  1. How to implement Comparable interface

implement 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.

  • 0 if the values are equal.
  • 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;
/*from ja v  a2 s.c  o  m*/
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:

Next chapter...

What you will learn in the next chapter:

  1. Get Enumeration from collection, create list from Enumeration
Home » Java Tutorial » Collections
Iterator
ListIterator
Collection unmodifiable
Collection synchronized
Collection singleton
Collection max/min value
Empty Collections
Comparator
Comparable
Enumeration
EnumSet
EnumMap Class
PriorityQueue