11 MySQL_分組查詢和關聯查詢
阿新 • • 發佈:2022-05-10
HashSet
Hashset底層是雜湊表即陣列+連結串列+紅黑樹
儲存過程:
由hashcode計算資料儲存的位置,如果該位置為null,將資料新增進去,否則計算equals若為true,則不新增,否則與連結串列下一個元素進行equals比較
實踐
新增,刪除,遍歷,判斷跟List介面很相近
差別在於如果新建一個賦值完全相同的例項,想要認為其與原例項相同,需要重寫equals和hashcode方法,而List中僅需要重寫hashcode
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); } }