When to include what?

浪子不回头ぞ 提交于 2019-12-25 00:23:20

问题


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().



来源:https://stackoverflow.com/questions/10912914/when-to-include-what

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!