Set集合的方法全部来自于继承Collection
HashSet哈希表结构:数组+链表,1.8后再加红黑树 存储过程:- 先用hashCode计算存到哪个位置,为空直接保存再用equals判断是否重复不重复就串一个单向链表
HashSet判断重复项的依据有两项
先是hashCode再是equals这两个方法返回的结果都是相等,才判定为重复 Student实体类 基本配置
public class Student implements Comparable重写hashCode(){ public String name; public int age; public char sex; public Student(){} public Student(String name,int age,char sex){ this.age = age; this.name = name; this.sex = sex; }
相同数据的字段的hashCode值都是一样的:都是从常量池取值重写hashCode本质:就是判断各个属性的hashCode值,是否相等 为什么乘以31:
31是一个素质数(只有1和它本身两个因数),可以减少散列冲突,尽量让计算结果不同
提高执行效率:31*i = (i << 5) -i:31本身就是2的4次方-1
这是数学家们应该探讨的问题,我们只要知道这个事情就可以了
@Override
public int hashCode() {
//return (this.sex + this.age + this.name).hashCode() * 31;
return Objects.hash(name, age, sex);
}
重视equals()
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if(o instanceof Student){
Student student = (Student) o;
return age == student.age && sex == student.sex && Objects.equals(name, student.name);
}
return false;
}
main()
package com.li.changGe.collections.setGather;
import com.li.changGe.pojo.Student;
import java.util.HashSet;
import java.util.Set;
public class HashSetDemo01 {
public static void main(String[] args) {
Set set = new HashSet();
Student student = new Student("长歌",18,'女');
Student student1 = new Student("世民",22,'男');
Student student2 = new Student("则天",20,'女');
set.add(student);
set.add(student1);
set.add(student2);
//------------------------------------------------
set.add(new Student("长歌",18,'女'));
System.out.println("长度:"+set.size()+"n"+set);
}
}



