Java Reference
In-Depth Information
}
public String toString() {
return person.toString() + '\n' + number.toString();
}
// Read an entry from the keyboard
public static BookEntry readEntry() {
return new BookEntry(Person.readPerson(), PhoneNumber.readNumber());
}
private Person person;
private PhoneNumber number;
}
This is all pretty standard stuff. In the static method readEntry() , we just make use of the methods
that read Person and PhoneNumber objects so this becomes very simple.
Now we come to the class that implements the phone book - called the PhoneBook class, of course:
import java.io.*;
import java.util.*;
class PhoneBook implements Serializable {
public void addEntry(BookEntry entry) {
phonebook.put(entry.getPerson(), entry);
}
public BookEntry getEntry(Person key) {
return (BookEntry)phonebook.get(key);
}
public PhoneNumber getNumber(Person key) {
return getEntry(key).getNumber();
}
private HashMap phonebook = new HashMap();
}
To store BookEntry objects we use a HashMap member, phonebook . We will use the Person object
corresponding to an entry as the key, so the addEntry() method only has to retrieve the Person
object from the BookEntry object that is passed to it, and use that as the first argument to the put()
method for phonebook . Note that when we retrieve an entry, we must cast the object that is returned
by the get() method to the BookEntry type, as get() returns type Object . All we need now is a
class containing main() to test these classes:
class TryPhoneBook {
public static void main(String[] args) {
PhoneBook book = new PhoneBook(); // The phone book
FormattedInput in = new FormattedInput(); // Keyboard input
Person someone;
Search WWH ::




Custom Search