由hash表来表示jdk1.8之前:数组+链表
jdk1.8及之后:数组+链表+红黑树
假设:底层是一个数组,数组长度是8,每个储存的数据,根据计算对应的hashCode然后再计算对应的索引,
每个下标中存放的其实是一个链表,然后就调用equlas方法,比较数据是否在此链表中重复,重复的话不储存
不重复就添加到尾部
【在jdk1.8之后,当数组中某一个索引下对应的链表长度过长,不利于查找时候,会自动转换为红黑树储存】
import java.util.HashSet; import java.util.Objects; public class Class005_hashSet { public static void main(String[] args) { HashSetpsons = new HashSet<>(); psons.add(new Person002("zhangsan",18)); psons.add(new Person002("zhangsan",19)); psons.add(new Person002("zhangsan",18)); for (Person002 pson : psons) { System.out.println(pson); } } } class Person002{ private String name; private int age; public Person002() { } public Person002(String name, int age) { this.name = name; this.age = age; } 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 boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Person002 person = (Person002) o; return age == person.age && Objects.equals(name, person.name); } @Override public int hashCode() { return Objects.hash(name, age); } @Override public String toString() { return "Person002{" + "name='" + name + ''' + ", age=" + age + '}'; } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)