1. 定义学生类Student,属性:姓名、性别、年龄
public class Student {
    private String name;
    private String gender;
    private int age;
    
    public Student(String name, String gender, int age) {
        this.name = name;
        this.gender = gender;
        this.age = age;
    }
    
    // getter和setter方法省略
    
    // 重写equals()和hashCode()方法,用于判断对象相等
    @Override
    public boolean equals(Object obj) {
        if(obj == null) return false;
        if(this == obj) return true;
        if(obj instanceof Student) {
            Student s = (Student)obj;
            if(this.name.equals(s.getName()) && this.gender.equals(s.getGender()) && this.age == s.getAge()) {
                return true;
            }
        }
        return false;
    }
    
    @Override
    public int hashCode() {
        return Objects.hash(name, gender, age);
    }
}
  1. 定义测试类及main()方法
import java.util.HashSet;
import java.util.Set;

public class Test {
    public static void main(String[] args) {
        // 创建三个Student对象
        Student s1 = new Student("张三", "男", 20);
        Student s2 = new Student("李四", "女", 21);
        Student s3 = new Student("张三", "男", 20);
        
        // 定义一个存储Student类型的HashSet集合
        Set<Student> set = new HashSet<>();
        
        // 将上述对象存储到Set集合中,要求集合中不能存储姓名,性别,年龄相同的元素。
        set.add(s1);
        set.add(s2);
        set.add(s3);
        
        // 使用增强for遍历集合,获取集合中每个Student对象,并打印属性值;
        for(Student s : set) {
            System.out.println(s.getName() + "," + s.getGender() + "," + s.getAge());
        }
    }
}

本示例中,我们定义了Student类,并重写了equals()和hashCode()方法,用于判断两个Student对象是否相同。在测试类中,我们创建了三个Student对象,并使用HashSet集合存储它们。由于HashSet集合根据对象的hashCode()和equals()方法进行去重,因此最终集合中只包含两个不同的Student对象:

  • 张三, 男, 20
  • 李四, 女, 21

这展示了如何使用HashSet集合以及重写equals()和hashCode()方法来有效地存储和管理自定义对象,并确保集合中没有重复元素。

Java HashSet去重: 使用Student类存储学生信息并去除重复元素

原文地址: https://www.cveoy.top/t/topic/okxq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录