I created a class Person
(as the book says) to hold the name and last name of a person entered from the keyboard and then there is another class PhoneNumber
which encapsulates the country code, area code and the number of a person as a String.
Person is intended to be used as the key in a Hashmap.
Class BookEntry
encapsulates both Person
and PhoneNumber
. A lot of BookEntry
objects make up a HashMap that represents a phonebook.
Person
implements Comparable<Person>
so it contains CompareTo(Person)
method. Later the book adds equals(Object anotherPerson)
method.
My question is, isn't the CompareTo
method enough for comparing two keys? or is it that the internal mechanics of the HashMap<> requires me to include equals()
method to compare two keys?
compareTo()
public int compareTo(Person person) {
int result = lastName.compareTo(person.lastName);
return result==0? firstName.compareTo(person.firstName):result;
}
equals()
public boolean equals(Object anotherPerson){
return compareTo((Person)person)==0;
}
compareTo()
method is used in sorting,
This method's implementation will determine who is greater(lesser, same) between two person, also at what degree
while equals()
& hashcode()
will be used in Hash based data structure (HashMap) in your case
user-defined class as a key of HashMap
yes you need to implement hashcode()
and equals()
properly
Also See