HashSet contains problem with custom objects

前端 未结 4 1112
旧时难觅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:34

    Hashes are simple pairing of key and values. Here's how the state of your code would look before and after the renaming in pseudo-code:

    Before:

    personSet => {
        SOME_NUM1 => Person(name=>"raghu", 12),
        SOME_NUM2 => Person(name=>"rimmu", 21)
    }
    
    p1.setName("raghus"); #p1.hashcode() = SOME_NEW_NUM
    p1.setAge(13);#p1.hashcode() = SOME_OTHER_NEW_NUM
    

    After:

    personSet => {
        SOME_NUM1 => Person(name=>"raghu", 13),
        SOME_NUM2 => Person(name=>"rimmu", 21)
    }
    

    Since you have direct access to the p1 the object within the HashSet is updated correctly, but HashSet does not pay attention to contained objects hashcodes being updated. When a call to personSet.contains(p1) is called, the HashSet looks for an entry with the new value of p1.hashcode().

    The p1 object is associated with its previous hashcode at the time when it was added to the HashSet.

提交回复
热议问题