Comparable Interface

Objects that have an ordering are compared using the compareTo() method.

18. Entry Testing Program


When the entries of a dictionary are put in order, does the order depend on the definition? No.

Should the compareTo() method depend on the definition? No.

Fill in the blank to complete the compareTo() method.

  public int compareTo( Entry other )
   return getWord().compareTo( other.getWord() );

Another solution is:

  public int compareTo( Entry other )
   return word.compareTo( other.word );

Entry Testing Program

Here is a program that tests that the Entry class works as expected.

import java.util.Arrays;

class Entry implements Comparable<Entry>
  .  .  .

class EntryTester
  public static void main ( String[] args )
    Entry[] wordList = new Entry[10];
    wordList[0] = new Entry( "WWW", "World Wide Web" );
    wordList[1] = new Entry( "HTTP","Hypertext Transport Protocol" );
    wordList[2] = new Entry( "DNS", "Domain Name System" );
    wordList[3] = new Entry( "AWT", "Application Windowing Toolkit" );
    wordList[4] = new Entry( "CPU", "Central Processing Unit" );
    wordList[5] = new Entry( "RAM", "Random Access Memory" );
    wordList[6] = new Entry( "URL", "Uniform Resource Locator" );
    wordList[7] = new Entry( "GUI", "Graphical User Interface" );
    wordList[8] = new Entry( "API", "Application Programming Interface" );
    wordList[9] = new Entry( "ROM", "Read-only Memory" );
    Arrays.sort( wordList );
    for ( int j=0; j<wordList.length; j++ )
      System.out.println( wordList[j].toString() );


The program outputs:

API Application Programming Interface
AWT Application Windowing Toolkit
DNS Domain Name System
CPU Central Processing Unit
GUI Graphical User Interface
ROM Read-only Memory
HTTP Hypertext Transport Protocol
RAM Random Access Memory
URL Uniform Resource Locator
WWW World Wide Web

The sort() method used our compareTo() to determine the order of the entries.

Question 18:

Must an array be in sorted order for it to be searched?