一、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);
}
}
}
标签:Set,name,HashSet,子类,age,set1,Student,public
From: https://www.cnblogs.com/ndmtzwdx/p/18469437