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的对象都添加进去了?怎么不起作用?
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的对象都添加进去了?怎么不起作用?
public int hashcode(){
return id.hashCode();
}方法中C需要大写,不然不算重写
public int hashcode(){
return id.hashCode();
}方法中C需要大写,不然不算重写
厉害了,我说我怎么找不到错误呢
public int hashCode() {
return super.hashCode();
}