HashSet
HashSet
Hashset底层是哈希表即数组+链表+红黑树
存储过程:
由hashcode计算数据存储的位置,如果该位置为null,将数据添加进去,否则计算equals若为true,则不添加,否则与链表下一个元素进行equals比较
实践
添加,删除,遍历,判断跟List接口很相近
差别在于如果新建一个赋值完全相同的实例,想要认为其与原实例相同,需要重写equals和hashcode方法,而List中仅需要重写equals
package com.qianfeng.collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Objects;
/**
* 功能描述
*
* @since 2022-05-13
*/
public class HashSetDemo {
public static void main(String[] args) {
HashSet hashSet = new HashSet();
Person person = new Person("zhangsan", 1);
Person person1 = new Person("lisi", 2);
Person person2 = new Person("wangwu", 3);
hashSet.add(person);
hashSet.add(person1);
hashSet.add(person2);
hashSet.remove(person2);
Iterator iterator = hashSet.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
System.out.println(hashSet.isEmpty());
System.out.println(hashSet.contains(person));
System.out.println(hashSet.contains(new Person("zhangsan", 1)));
}
}
class Person {
private String name;
private Integer age;
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Preson{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Person person = (Person) o;
return Objects.equals(name, person.name) && Objects.equals(age, person.age);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}