HashSet存储元素的流程
当调用HashSet集合的add()方法存入元素时,首先调用HashSet集合的hashCode()方法获得元素对象的哈希值,然后根据对象的哈希值计算出一个存储位置。如果该位置上没有元素,则直接将元素存入。如果该位置上有元素存在,则会调用equals()方法让当前存入的元素和该位置上的元素进行比较,如果返回的结果为false,就将该元素存入集合,返回的结果为true,则说明有重复元素,就将需要存入的重复元素舍弃。

测试类
import entity.Student;
import entity.Student2;
import java.util.LinkedHashSet;
/**
* HashSet 如何判断重复元素测试
* @author : ZhouMei
* @date Date : 2022年08月11日 16:14
* @Description: TODO
*/
public class LinkedHashSetTest {
public static void main(String[] args) {
LinkedHashSet set = new LinkedHashSet();
set.add(new Student(1, "张三", 23));
set.add(new Student(2, "李四", 18));
set.add(new Student(3, "王五", 22));
set.add(new Student(4, "赵六", 21));
set.add(new Student(4, "赵六2", 21));
System.out.println("未重写hashCode和equals方法:" + set);
LinkedHashSet set2 = new LinkedHashSet();
set2.add(new Student2(1, "张三", 23));
set2.add(new Student2(2, "李四", 18));
set2.add(new Student2(3, "王五", 22));
set2.add(new Student2(4, "赵六", 21));
set2.add(new Student2(4, "赵六2", 21));
System.out.println("重写hashCode和equals方法:" + set2);
}
}
package entity;
import lombok.Data;
/**
* @author : ZhouMei
* @date Date : 2022年08月11日 10:20
* @Description: TODO
*/
@Data
public class Student implements Comparable {
private Integer id;
private String name;
private Integer age;
public int compareTo(Object o1) {
Student s1 = (Student) o1;
if(this.age > s1.age){
return 1;
}
if(this.age == s1.age){
return this.name.compareTo(s1.name);
}
return -1;
}
public Student(Integer id, String name, Integer age){
this.id = id;
this.name = name;
this.age = age;
}
}
package entity;
import lombok.Data;
/**
* @author : ZhouMei
* @date Date : 2022年08月11日 10:20
* @Description: TODO
*/
@Data
public class Student2 implements Comparable {
private Integer id;
private String name;
private Integer age;
public int compareTo(Object o1) {
Student2 s1 = (Student2) o1;
if(this.age > s1.age){
return 1;
}
if(this.age == s1.age){
return this.name.compareTo(s1.name);
}
return -1;
}
public Student2(Integer id, String name, Integer age){
this.id = id;
this.name = name;
this.age = age;
}
/**
* 重写hashCode方法
*/
public int hashCode() {
//返回id属性的哈希值
return id.hashCode();
}
/**
* 重写equals方法
*/
public boolean equals(Object obj) {
//判断是否是同一个对象,如果是,直接返回true
if (this == obj) {
return true;
}
//判断对象是为Student2类型
if (!(obj instanceof Student2)) {
return false;
}
//将对象强转为Student2类型
Student2 student2 = (Student2) obj;
//判断id值是否相同
boolean b = this.id.equals(student2.getId());
//返回判断结果
return b;
}
}
未重写hashCode和equals方法:[Student(id=1, name=张三, age=23), Student(id=2, name=李四, age=18), Student(id=3, name=王五, age=22), Student(id=4, name=赵六, age=21), Student(id=4, name=赵六2, age=21)]
重写hashCode和equals方法:[Student2(id=1, name=张三, age=23), Student2(id=2, name=李四, age=18), Student2(id=3, name=王五, age=22), Student2(id=4, name=赵六, age=21)]