Comparable Interface
Objects that have an ordering are compared using the compareTo() method.
17. Dictionary Entry
Answer:
The class must implement Comparable
.
Dictionary Entry
Say that you are writing a program that acts like a dictionary. A dictionary entry has two instance variables: the word that it defines and the definition.
A class that implements Comparable<T>
must implement the method int compareTo( T other )
where T
is the type of the class.
Since our Entry
implements the Comparable<Entry>
interface, it must implement the method int compareTo( Entry other )
.
class Entry implements Comparable<Entry> { private String word; private String definition; public Entry ( String word, String definition ) { this.word = word; this.definition = definition; } public String getWord() { return word; } public String getDefinition() { return definition; } public String toString() { return getWord() + "\t" + getDefinition(); } public int compareTo( Entry other ) { return ; } } |
Question 17:
When the entries of a dictionary are put in order, does the order depend on the definition?
Should the compareTo()
method depend on the definition?
Fill in the blank to complete the compareTo()
method.
Hint: use the compareTo()
method of the String
.