Java Reference
In-Depth Information
import java.io.Serializable;
class BookEntry implements Comparable<BookEntry>, Serializable {
public int compareTo(BookEntry entry) {
return person.compareTo(entry.getPerson());
}
// Rest of the class as before...
}
Directory "TryPhoneBook 2"
When sorting the entries, you want the sort order of the Person objects to determine the sort order of the
BookEntry objects. Because the Person class already implements the Comparable<> interface, you can
implement the compareTo() method in the BookEntry class by calling the method for the Person object
in the entry.
Now you can implement the listEntries() method in the PhoneBook class to list the entries in alpha-
betical order:
import java.nio.file.*;
import java.io.*;
import java.util.*;
class PhoneBook implements Serializable {
// List all entries in the topic
public void listEntries() {
// Get the entries as a linked list
LinkedList<BookEntry> entries = new
LinkedList<>(phonebook.values());
Collections.sort(entries);
// Sort the entries
for(BookEntry entry : entries) {
System.out.println(entry);
}
}
// Other members as before...
}
Directory "TryPhoneBook 2"
Listing the entries in name sequence is relatively simple. Calling the values() method for the phone-
book object returns the objects in the map, which are BookEntry objects, as a Collection<> . You
pass this to the constructor for the LinkedList<BookEntry> class to obtain a list of entries. The
LinkedList<> class implements the List<> interface, so you can pass the entries object to the sort()
Search WWH ::




Custom Search