关于HashSet添加元素问题,大神来帮我看看

SKY862390450 SKY862390450 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
import java.util.*;
class employee{
private String id;
private String name;
private String age;
private String salary;
public employee(String id,String name,String age,String salary){
this.id=id;
this.name=name;
this.age=age;
this.salary=salary;
}
public String toString(){
return id+":"+name+","+age+","+salary+"";

}
public int hashcode(){
return id.hashCode();
}
public boolean equals(Object obj){
if(this==obj){
return true;
}
if(!(obj instanceof employee)){
return false;
}
employee emp=(employee)obj;
boolean b=this.id.equals(emp.id);
return b;

}

}
public class information {

public static void main(String[] args) {


HashSet hs=new HashSet();
employee emp1=new employee("5","张三","25","3500");
employee emp2=new employee("2","李四","30","4000");
employee emp3=new employee("5","王五","40","5000");
hs.add(emp1);
hs.add(emp2);
hs.add(emp3);
System.out.print(hs);

}


}

我改写了hashcode()和equals()方法,为什么emp1和emp3这两个id都为5的对象都添加进去了?怎么不起作用?
...全文
评论 8
收藏 已收藏
分享
返回顶部
SKY862390450
Java SE 62,621 成员 307,251 内容