HashSet是Set接口胡一个实现类,它所存储的元素是不重复的,并且元素都是无序的.
HashSet集合之所以能确保不出现重复的元素,是因为当调用HashSet集合的add方法时首先调用当前存入对象的hashCode方法获得对象的哈希值,然后根据对象的哈希值计算出一个存储位置如果该位置上没有元素,则直接将元素存入,如果存在元素,则会调用equals方法(比较对象是否相等)让当前存入的元素依次和该位置上的元素比较。返回false则存入,true则舍弃
public class Test {
public static void main(String[] args) {
HashSet<Student> hs=new HashSet<Student>();
Student s1=new Student("1","Jack");
Student s2=new Student("2", "Rose");
Student s3=new Student("2", "Rose");
hs.add(s1);
hs.add(s2);
hs.add(s3);
System.out.println(hs);
/*******************hashCode******************/
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
System.out.println(s3.hashCode());
/*****************equals********************/
System.out.println("s2是否等于s3:"+s2.equals(s3));
}
}
class Student{
String id;
String name;
public Student() {
super();
}
public Student(String id, String name) {
super();
this.id = id;
this.name = name;
}
//重写toString方法
public String toString() {
return this.id+":"+this.name;
}
}
之所以出现重复元素是在定义Student类时没有重写hashCode和equals方法
public class Test {
public static void main(String[] args) {
HashSet<Student> hs = new HashSet<Student>();
Student s1 = new Student("1", "Jack");
Student s2 = new Student("2", "Rose");
Student s3 = new Student("2", "Rose");
hs.add(s1);
hs.add(s2);
hs.add(s3);
System.out.println(hs);
/******************* hashCode ******************/
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
System.out.println(s3.hashCode());
/***************** equals ********************/
System.out.println("s2是否等于s3:" + s2.equals(s3));
}
}
class Student {
String id;
String name;
public Student() {
super();
}
public Student(String id, String name) {
super();
this.id = id;
this.name = name;
}
// 重写toString方法
public String toString() {
return this.id + ":" + this.name;
}
// 重写hashCode方法
public int hashCode() {
return this.id.hashCode();
}
// 重写equals方法
public boolean equals(Object obj) {
if (this == obj) { // 判断是否是同一个对象
return true;
}
if (!(obj instanceof Student)) { // 如果不是Student类型,返回false
return false;
}
Student student = (Student) obj;
boolean b = this.id.equals(student.id);
return b;
}
}