展开全部
因为你只重写了equals方法 没有重写hashCode方法
HashSet 判断元素是否相等 , 首先调用e68a843231313335323631343130323136353331333337623534hashCode方法,
如果hashCode的值一样, 那么调用equals方法,
如果equals方法也一样, 那么才算重复元素, 不在添加
所以没有重写hashCode方法的时候, stu2和stu3的hashCode值不一样,
你就可以添加两次相同的元素
修改后的代码import java.util.*;
class Student {
private String id;
private String name;
public Student(String id, String name) {
this.id = id;
this.name = name;
}
public String toString() {
return id + ":" + name;
}
public int HashCode() {
return this.id.hashCode();
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Student)) {
return false;
}
Student stu = (Student) obj;
boolean b = this.id.equals(stu.id);
return b;
}
public int hashCode() {//重写hashCode方法
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
}
public class xuexi {
public static void main(String[] args) {
HashSet hs = new HashSet();
Student stu1 = new Student("1", "Jack");
Student stu2 = new Student("2", "Rose");
Student stu3 = new Student("2", "Rose");
hs.add(stu1);
hs.add(stu2);
hs.add(stu3);
System.out.println(hs);
}
}
测试[2:Rose, 1:Jack]