When to include what?

2019-08-28 06:33发布

问题:

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;
}

回答1:

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

  • overriding-equals-and-hashcode-in-java


回答2:

Some data structures will use compareTo (for example a TreeMap) and some will use equals (for example a HashMap).

More importantly, it is strongly recommended that compareTo and equals be consistent, as explained in the Comparator javadoc:

It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact. The recommended language is "Note: this class has a natural ordering that is inconsistent with equals."

Another hint, found in TreeMap javadoc (emphasis mine):

Note that the ordering maintained by a tree map, like any sorted map, and whether or not an explicit comparator is provided, must be consistent with equals if this sorted map is to correctly implement the Map interface.

Finally, if you override equals you should also override hashcode to prevent unexpected behaviours when using hash-based structures.



回答3:

HashMap uses equals() and not compareTo(), so you have to implement it. TreeMap uses compareTo().