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方法后,重复的对象不会被添加,运行结果为:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!