在Set集合中添加自定义的对象

讨论的问题:众所周知,set集合的特点是无重复的元素。一般Java类库中的类型比如String 类在添加到set中后,是不会出现重复现象的。那么自定义的类呢?

1.创建自定义类

public class Dog {
    private String name;
    private String kind;
    private String hobby;
    
    public Dog(String name,String kind,String hobby) {
        this.hobby=hobby;
        this.kind=kind;
        this.name=name;
    }

    public String getName() {
        return name;
    }

    public String getKind() {
        return kind;
    }

    public String getHobby() {
        return hobby;
    }

    @Override
    public String toString() {
        return "Dog [name=" + name + ", kind=" + kind + ", hobby=" + hobby + "]";
    }

2.测试

public class TestSet {

    public static void main(String[] args) {
        
        Set<Dog> dogs=new HashSet<>();
        
        Dog dog=new Dog("huahua","tianyuan","run");
        Dog dog1=new Dog("tiantian","hashiqi","eat");
        Dog dog2=new Dog("qiqi","jinmao","smell");
        Dog dog3=new Dog("qiqi","jinmao","smell");
        dogs.add(dog);
        dogs.add(dog1);
        dogs.add(dog2);
        dogs.add(dog3);
        System.out.println(dogs);
    }
}

3.结果:

[Dog [name=qiqi, kind=jinmao, hobby=smell], Dog [name=huahua, kind=tianyuan, hobby=run], Dog [name=tiantian, kind=hashiqi, hobby=eat], Dog [name=qiqi, kind=jinmao, hobby=smell]]

4.分析:

可以看到在结构中有两个重复的元素。

自定义类的情况下,需要重写hashcode()和equals()方法,Object中的equals()仅能判断两个对象是否具有相同的引用,不能判断对象的内容细节,所以需要重写。

Note:hashcode是根据类的实例域生成的一个随机的整数,可为负。只要两个对象相同,他们的hashcode码就相同。

5.改进:在Dog类中重写如下方法:

@Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((hobby == null) ? 0 : hobby.hashCode());
        result = prime * result + ((kind == null) ? 0 : kind.hashCode());
        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;
        Dog other = (Dog) obj;
        if (hobby == null) {
            if (other.hobby != null)
                return false;
        } else if (!hobby.equals(other.hobby))
            return false;
        if (kind == null) {
            if (other.kind != null)
                return false;
        } else if (!kind.equals(other.kind))
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }

6.结果:

[Dog [name=tiantian, kind=hashiqi, hobby=eat], Dog [name=qiqi, kind=jinmao, hobby=smell], Dog [name=huahua, kind=tianyuan, hobby=run]]

不再有重复的元素!

 

上一篇:kubernetes1.14部署kube-dashboard:


下一篇:类、对象