zur vorherigen Seite   zum Inhaltsverzeichnis   zur nächsten Seite

Antwort:

Wenn die Einträge eines Wörterbuchs sortiert werden, hängt die Reihenfolge dann von der Definition ab? Nein.

Sollte die Methode compareTo() von der Definition abhängen? Nein.

Wir füllen die Lücke aus, um die Methode compareTo() zu vervollständigen.

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

Eine andere Lösung ist:

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

Entry Testprogramm

Hier ist ein Programm, das testet ob die Entry-Klasse wie erwartet funktioniert.

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
CPU     Central Processing Unit
DNS     Domain Name System
GUI     Graphical User Interface
HTTP    Hypertext Transport Protocol
RAM     Random Access Memory
ROM     Read-only Memory
URL     Uniform Resource Locator
WWW     World Wide Web

Die Methode sort() verwendet unsere Methode compareTo(), um die Reihenfolge der Einträge zu bestimmen.


FRAGE 18:

Muss ein Array sortiert sein, damit es durchsucht werden kann?

zur vorherigen Seite   zum Inhaltsverzeichnis   zur nächsten Seite