HashSet contains problem with custom objects

前端 未结 4 1114
旧时难觅i
旧时难觅i 2020-12-05 11:06

My Custom class that will be contained by HashSet

public class Person {
    String name;
    int age;

    public Person(String name, int age) {
        this         


        
4条回答
  •  臣服心动
    2020-12-05 11:44

    I think you need to have hashCode depends on mutable fields quite often indeed: when you override equals that depends on mutable fields.

    From hashCode's contract: "If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result."

    So, if you create two objects such that A.equals(B) is true, and then modify A such a way that you get A.equals(B) became false, you need to have hashCodes change too.

    It's true that in hashCode's documentation is stated that "It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results.", but I don't know how this can help.

提交回复
热议问题