Java Reference
In-Depth Information
We have waded through a lot of the theory for HashMap objects; let's put together an example that
applies it.
We can put together a very simple phone book that uses a map. We won't worry too much about error
recovery so that we don't bulk up the code too much. We will reuse the Person class that we saw
earlier, and the FormattedInput class with the modified version of the readString() method, plus
the InvalidUserInputException class, so copy them to a new directory called TryHashMap or
something similar. Besides the Person class we will need a PhoneNumber class, plus an Entry class
that represents an entry in our phone book combining the name and number. We could add other stuff
such as the address, but this is not necessary to show the principles. We will also define a PhoneBook
class to represent the phone book.
Try It Out - Using a HashMap Map
We need to improve our old Person class to make Person objects usable as keys in the map that we will
use - to store the phone book entries. We must add an equals() method and we'll override the default
hashCode() method just to show how this can work. The extended version of the class will be as follows:
public class Person implements Comparable, Serializable {
public boolean equals(Object person) {
return compareTo(person) == 0;
}
public int hashCode() {
return 7*firstName.hashCode()+13*surname.hashCode();
}
// The rest of the class as before...
}
Since the String class defines a good hashCode() method, we can easily produce a hash code for a
Person object from the data members. To implement the equals() method we just call the method
that we implemented for the Comparable interface. As it is likely to be required in this application, we
have made the class serializable
There's another thing we could do that will be useful. We could add a static method to read data for
a Person object from the keyboard:
import java.io.*;
public class Person implements Comparable, Serializable {
// Read a person from the keyboard
public static Person readPerson() {
FormattedInput in = new FormattedInput();
// Read in the first name and remove blanks front and back
System.out.println("\nEnter first name:");
String firstName = in.readString().trim();
// Read in the surname, also trimming blanks
System.out.println("Enter surname:");
Search WWH ::




Custom Search