一、HashSet的特點:
底層資料結構是雜湊表,查詢速度快,且元素唯一
二、HashSet的使用特點:
1.向HashSet集合中新增基本資料型別或者String元素的時候會自動去重
import java.util.HashSet;
public class HashSetDemo1 {
public static void main(String[] args) {
//使用HashSet儲存字串元素
HashSet<String> set1 = new HashSet<>();
//新增元素
set1.add("hello");
set1.add("world");
set1.add("hello");
set1.add("java");
set1.add("hello");
set1.add("hadoop");
System.out.println("set1: " + set1);
}
}
2.當我們傳入的資料是一個具體類物件的時候:若想要使用HashSet對元素進行去重,需要元素型別本身重寫hashCode方法和equals方法
1.先編寫一個學生類,裡面需要重寫hashCode方法和equals方法才能進行去重
import java.util.Objects;
public class Student {
private String name;
private int age;
public Student() {
}
public Student(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;
Student student = (Student) o;
return age == student.age && Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
2.編寫測試類,建立類物件,並進行賦值
import java.util.HashSet;
public class HashSetDemo2 {
public static void main(String[] args) {
//使用HashSet儲存學生物件元素,當學生的姓名和年齡一樣的時候,認為重複了
HashSet<Student> set1 = new HashSet<>();
Student s1 = new Student("李剛", 18);
Student s2 = new Student("錢志強", 16);
Student s3 = new Student("劉亦菲", 18);
Student s4 = new Student("李剛", 18);
Student s5 = new Student("吳問強", 19);
set1.add(s1);
set1.add(s2);
set1.add(s3);
set1.add(s4);
set1.add(s5);
for (Student student : set1) {
System.out.println(student);
}
}
}