0
点赞
收藏
分享

微信扫一扫

一道关于HashSet的题

玩物励志老乐 2022-02-12 阅读 87

代码如下:

class Person {

    private int id;
    public String name;

    public Person(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return id == person.id && Objects.equals(name, person.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name);
    }
}
public static void main(String[] args) {
        HashSet set = new HashSet();
        Person p1 = new Person(1001, "aa");
        Person p2 = new Person(1002, "bb");
        set.add(p1);
        set.add(p2);
        p1.name = "cc";
        set.remove(p1);
        System.out.println(set);//1
        set.add(new Person(1001,"cc"));
        System.out.println(set);//2
        set.add(new Person(1001,"aa"));
        System.out.println(set);//3


    }

尝试分析第1,2,3次分别输出什么

分析:
第一次输出(1001,cc)和(1002,bb)。因为第一次添加的p1的hash值为123(假设),修改之后aa变为了cc,但p1的hash仍为123,执行remove(p1)时根据(1001,cc)的hash值(124)找索引,发现为空,所以remove失败。
第二次会输出(1001,cc)和(1002,bb)和(1001,cc)。因为新的(1001,cc)的新的hash值为125.
第三次会输出(1001,cc)和(1002,bb)和(1001,cc)和(1001,aa)。因为根据hash计算,新的(1001,aa)与原(1001,aa)(变成了(1001,cc))相同,所以会挂在hash值为123的(1001,cc)后面。

举报

相关推荐

0 条评论