You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java如何实现无重复数据集合?兼处理索引访问需求

如何在Java中实现无重复的对象集合(用于关联Course与Student)

问题背景

需要创建无重复数据的集合,曾纠结是否要保留索引以通过get(0)这类方式访问元素,但实际场景中索引并非必需;同时要建立Course与Student对象的关联,避免两者出现重复数据,且不希望用Java文档不推荐的“条件过滤列表去重”方式。

解决方案

直接使用Set集合即可,完全满足无重复的需求,以下是具体实现要点:

1. 重写对象的equals()和hashCode()方法

Set集合依赖这两个方法判断对象是否重复,必须在Course和Student类中基于唯一标识(比如学号、课程ID)重写这两个方法,示例如下:

import java.util.Objects;

public class Student {
    private String studentId; // 唯一标识
    private String name;

    // 构造方法、Getter/Setter
    public Student(String studentId, String name) {
        this.studentId = studentId;
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return Objects.equals(studentId, student.studentId);
    }

    @Override
    public int hashCode() {
        return Objects.hash(studentId);
    }

    // Getter方法
    public String getName() {
        return name;
    }
}

Course类同理,基于课程ID重写equals()和hashCode()。

2. 使用Set实现无重复集合

  • 基础去重用HashSet:性能最优,默认不保证顺序
Set<Student> studentSet = new HashSet<>();
studentSet.add(new Student("S001", "张三"));
studentSet.add(new Student("S001", "张三")); // 重复对象,不会被添加到集合中
  • 需要保留插入顺序用LinkedHashSet:既保证无重复,又能按插入顺序遍历元素
Set<Student> orderedStudentSet = new LinkedHashSet<>();
orderedStudentSet.add(new Student("S001", "张三"));
orderedStudentSet.add(new Student("S002", "李四"));

// 遍历访问元素,替代索引访问的需求
for (Student student : orderedStudentSet) {
    System.out.println(student.getName());
}

3. 为什么不推荐用List去重?

Java文档不推荐手动遍历List并通过条件判断去重,这种方式不仅时间复杂度高(O(n²)),还容易因逻辑疏漏导致重复数据残留;而Set集合本身就内置了去重逻辑,代码更简洁、效率更高,完全适配你的需求。

内容的提问来源于stack exchange,提问作者Vinícius Silvano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 18:01:23