Comparable Example
Home ] Up ] Comparable Interface ] Comparator Interface ] Collections Class ] [ Comparable Example ] Comparator Example ] General Applicability ]

 

 

Here's an example of sorting, using the Comparable interface.

Note that String is defined to implement Comparable in JDK 1.2 and beyond.  We are using String's natural ordering, as defined by its compareTo method.

package examples;
import java.util.Collections;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ComparableSorter
{
  public static void main(String[] args)
  {
    List list = new ArrayList();
    list.add("abc");
    list.add("DEF");
    list.add("ghi");
    // Do the sort
    Collections.sort(list);
    // See results
    Iterator iter = list.iterator();
    while (iter.hasNext())
    {
      System.out.println(iter.next());
    }
  }
}

which outputs:

DEF
abc
ghi
As you can see, the natural ordering for Strings is case-sensitive.

 

This page was last modified on 02 October, 2007