Java Reference
In-Depth Information
TRY IT OUT: Using a HashMap Map
You need to improve your old
Person
class to make
Person
objects usable as keys in the map that you
use — to store the phone book entries. You must add an
equals()
method to do this, and you override
the default
hashCode()
method just to show how this can work. The extended version of the class is as
follows:
import java.io.*;
public class Person implements Comparable<Person>, Serializable {
@Override
public boolean equals(Object person) {
return compareTo((Person)person) == 0;
}
@Override
public int hashCode() {
return 7*firstName.hashCode()+13*surname.hashCode();
}
// The rest of the class as before...
private static final long serialVersionUID = 1001L;
}
Directory "TryPhoneBook 1"
You've added to the previous version of the class two methods that override the
equals()
and
hashCode()
methods inherited from
Object
and defined
serialVersionUID
for the class. Because the
String
class defines a good
hashCode()
method, you can easily produce a hash code for a
Person
ob-
ject from the data members. To implement the
equals()
method you just call the
compareTo()
method
that you implemented for the
Comparable<>
interface. You have also made the class serializable just in
case it comes in useful at some point.
There's another thing you can do that is definitely useful. You can add a
static
method to the
Person
class that reads data for a
Person
object from the keyboard:
import java.io.*;
public class Person implements Comparable<Person>, Serializable {
// Read a person from the keyboard
public static Person readPerson() {
String firstName = null;
String surname = null;