在Set集合中添加自定義的對象

討論的問題:衆所周知,set集合的特色是無重複的元素。通常Java類庫中的類型好比String 類在添加到set中後,是不會出現重複現象的。那麼自定義的類呢?ide

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.測試this

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.結果:spa

[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]]code

4.分析:對象

能夠看到在結構中有兩個重複的元素。blog

自定義類的狀況下,須要重寫hashcode()和equals()方法,Object中的equals()僅能判斷兩個對象是否具備相同的引用,不能判斷對象的內容細節,因此須要重寫。get

Note:hashcode是根據類的實例域生成的一個隨機的整數,可爲負。只要兩個對象相同,他們的hashcode碼就相同。hash

5.改進:在Dog類中重寫以下方法:class

@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]]

再也不有重複的元素!

相關文章
相關標籤/搜索