Java在HashSet中禁止添加重复对象

复制代码
package com.set;

public class Cat {
    private String name;
    private int month;
    private String species;
    //构造方法
    public Cat(String name, int month, String species) {
        this.name = name;
        this.month = month;
        this.species = species;
    }
    //get和set方法
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getMonth() {
        return month;
    }
    public void setMonth(int month) {
        this.month = month;
    }
    public String getSpecies() {
        return species;
    }
    public void setSpecies(String species) {
        this.species = species;
    }
    @Override
    public String toString() {
        return "Cat{" +
                "name='" + name + '\'' +
                ", month=" + month +
                ", species='" + species + '\'' +
                '}';
    }
}
复制代码
复制代码
package com.set;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class CatTest {
    public static void main(String[] args) {
        Cat huahua=new Cat("花花",12,"英国短毛猫");
        Cat fanfan=new Cat("凡凡",3,"中华田园猫");
        Set set=new HashSet();
        set.add(huahua);
        set.add(fanfan);
        Iterator it= set.iterator();
        while (it.hasNext()){
            System.out.println(it.next());
        }
        System.out.println("------------------------------");
        Cat huahua01=new Cat("花花",12,"英国短毛猫");
        set.add(huahua01);
        it=set.iterator();
        while(it.hasNext()){
            System.out.println(it.next());
        }
    }
}
复制代码

  add方法会调用hashCode、equals方法进行判断,此时未重写hashCode和equals方法,由于默认每个对象的hashCode值都不一样,重复的对象huahua01将会添加到集合中:

  

 

 

getClass()  和.class的作用:

        getClass()是Object类的方法,该方法的返回值类型是Class类,通过getClass()方法可以得到一个Class类的对象。而.class返回的也是Class类型的对象。所以,如果obj.getClass()和Cat.class返回的内容相等,说明是同一个对象。
       既然都可以得到Class的对象,关于getClass()和.class的区别:getClass()方法,有多态能力,运行时可以返回子类的类型信息。.class是没有多态的,是静态解析的,编译时可以确定类型信息。

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

    @Override
    public boolean equals(Object obj) {
        if(this==obj)
            return true;
        if(obj.getClass()==Cat.class){
            Cat cat=(Cat) obj;
            return cat.getName().equals(name)
                    && (cat.getMonth()==month)
                    && (cat.getSpecies().equals(species));
        }
        return false;
    }
复制代码

  在重写hashCode和equals方法后,重复的对象不会被添加,运行结果为:

  

 

posted @   南风知君  阅读(192)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示