HashSet集合的概述和特点
HashSet集合特点
- 底层数据结构是哈希表
- 不能保证存储和取出的顺序完全一致
- 没有带索引的方法,所以不能使用普通for循环遍历
- 由于是Set集合,所以元素唯一
常见数据结构之哈希表
JDK8以后底层进行优化,由数组+链表+红黑树进行实现。
HashSet1.7版本原理总结
- 底层结构 : 哈希表。(数组 +链表)
- 数组的长度默认为16,加载因子为0.75
- 首先会先获取元素的哈希值,计算出在数组中应存入的索引
- 判断该索引处是否为null
如果是null,直接添加
如果不是null,则与链表中所有的元素,通过equals方法比较属性值只要有一个相同,就不存,如果都不一样,才会存入集合
HashSet集合如果要存储自定义对象,并且不存储变量值相同的对象时,需要重写HashCode与equals方法。因为默认的哈希值是根据对象的地址值进行计算,而重写后的哈希值才是根据对象的属性值进行计算,故不加入重复元素。(如下)
HashSet<Student> hs = new HashSet<>();
Student s1 = new Student("fff",22);
Student s2 = new Student("xy",23);
Student s3 = new Student("fff",22);
hs.add(s1);
hs.add(s2);
hs.add(s3); //Student中已重写HashCode和equals方法,故重复的元素不进行添加。
for (Student h : hs) {
System.out.println(h);
}
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public Student() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
if (age != student.age) return false;
return name != null ? name.equals(student.name) : student.name == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + age;
return result;
}
输出结果: