Set集合首先来说它的特点有:元素是无序的(存入和取出的顺序不一定一致),元素不可重复。
这一篇主要是讲解Set集合里面的HashSet。
HashSet:底层的数据结构是哈希表。
那么问题来了,如果HashSet元素不可重复,那么HashSet是如何保证元素的唯一性的呢?
其实HashSet是通过元素的两个方法,Hashcode和eqauls来完成。
如果元素Hashcode相同,才会判断eqauls是否为true。
如果元素Hashcode不相同,会进一步调用eqauls判断元素是否相同。
注意,对于判断元素是否存在,以及删除等操作,依赖的方法是元素Hashcode和eqauls方法。
我们对HashSet主要也是需要了解它是怎么保证元素唯一性的。
我们可以通过如下代码简要的描述HashSet保证元素唯一性的过程:
package com.L.HashSet;
import java.util.HashSet;
import java.util.Iterator;
public class HashSetL {
public static void main(String[] args) {
HashSet hs = new HashSet();
hs.add(new Student("L01", 18));
hs.add(new Student("L02", 19));
hs.add(new Student("L02", 19));
hs.add(new Student("L03", 21));
hs.add(new Student("L03", 20));
hs.add(new Student("L04", 21));
Iterator it = hs.iterator();
while (it.hasNext()) {
Student stu = (Student) it.next();
System.out
.println("name:" + stu.getName() + ",age:" + stu.getAge());
}
}
}
class Student {
private String name;
private int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
public int hashCode() {
return name.hashCode() + age * 13;//使每个元素的哈希值都各不相同
}
public boolean equals(Object obj) {
if (!(obj instanceof Student)) {//若对象不是Student则对象不存入
return false;
}
Student stu = (Student) obj;
if (this.name.equals(stu.name)) {//判断是否有重复元素
System.out.println(stu.name + "有重复元素");
}
return this.name.equals(stu.name) && this.age == stu.age;//返回判断结果
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
总言之HashSet底层的数据结构是哈希表,由哈希表的性质我们可以知道,我们确保存入的元素具有不同的哈希值,我们就可以确保元素的唯一性。但是如果哈希值相同,我们就需要进一步的对元素经行比较,就是覆写equals方法。