记录一个使用Set去重复时遇到的问题

2018-03-08  本文已影响0人  sushengren

Set去重复机制:在往Set中插入新的对象时,首先会用该对象的hashCode()与集合中已经存在对象的hashCode()做比较,若返回false则可以插入,若返回true则进而比较equals();返回false则可以插入,返回true侧不能插入。

class User {

    private String name;

        public User(String name) {
        super();
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        User other = (User) obj;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }

}
        User user1 = new User("张三");
        User user2 = new User("张三");

        Set<User> set1 = new LinkedHashSet<User>();
        Set<User> set2 = new LinkedHashSet<User>();
        set1.add(user1);
        set2.add(user2);
        
        System.out.println("set1.remove(user2)--->" + set1.remove(user2));

结果:
set1.remove(user2)--->true

若直接改变Set中的元素,则出现的结果会不一样

        User user1 = new User("张三");
        User user2 = new User("李四");

        Set<User> set1 = new LinkedHashSet<User>();
        Set<User> set2 = new LinkedHashSet<User>();
        set1.add(user1);
        set2.add(user2);

        user1.setName("李四");

        System.out.println("set1.remove(user2)--->" + set1.remove(user2));

结果:
set1.remove(user2)--->false

至于为啥,我也不知道!

上一篇下一篇

猜你喜欢

热点阅读