1. Student 类设计
1.1 基本结构
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private String name;
private int age;
private String sex;
private String grade;
}
1.2 重写的方法
-
equals()方法:用于比较两个 [Student](file://D:\JAVAproject\JAVAplus\Test-day\src\com\stud\Student.java#L8-L37) 对象是否相等 -
hashCode()方法:为 [Student](file://D:\JAVAproject\JAVAplus\Test-day\src\com\stud\Student.java#L8-L37) 对象生成哈希码,支持HashSet去重 -
toString()方法:自定义对象的字符串表示形式
2. 集合类型对比
2.1 ArrayList
- 特点:有序、可重复
- 使用场景:需要保持插入顺序,允许重复元素
2.2 HashSet
- 特点:无序、不可重复
-
去重机制:基于
hashCode()和equals()方法 - 使用场景:需要去除重复元素
2.3 TreeSet
- 特点:自动排序、不可重复
-
排序机制:基于
Comparator或Comparable接口
3. TreeSet 自定义排序
3.1 使用 Comparator 接口
Set<Student> treeSet = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student t1, Student t2) {
// 按年龄大小排序,这只能针对于整数升序
return t1.getAge() - t2.getAge();
//如果出现小数的情况下,Int可能导致结果为0,可以调用Double包装类
//return Double.compare(t1.getAge(),t2.getAge()); //升序
}
});
3.2 Lambda 表达式简化写法
Set<Student> treeSet = new TreeSet<>((s1, s2) -> s1.getAge() - s2.getAge());
3.3 比较器返回值规则
- 负数:第一个对象小于第二个对象
- 0:两个对象相等
- 正数:第一个对象大于第二个对象
4. 实际运行效果
4.1 数据准备
Student s1 = new Student("张三", 18, "男", "2023级");
Student s2 = new Student("王五", 19, "女", "2024级");
Student s3 = new Student("赵六", 20, "男", "2025级");
Student s4 = new Student("张三", 18, "男", "2023级");
Student s5 = new Student("张三", 18, "男", "2023级");
4.2 各集合处理结果
- ArrayList:保留所有5个元素,包括重复项
- HashSet:去除重复后保留3个不同的 [Student](file://D:\JAVAproject\JAVAplus\Test-day\src\com\stud\Student.java#L8-L37) 对象
- TreeSet:按年龄排序后保留3个不同的 [Student](file://D:\JAVAproject\JAVAplus\Test-day\src\com\stud\Student.java#L8-L37) 对象
5. 关键知识点
5.1 去重机制
使用 HashSet 时,必须正确重写 equals() 和 hashCode() 方法以确保去重功能正常工作。
5.2 排序机制
使用 TreeSet 时,需要提供比较器来定义排序规则,或者让类实现 Comparable 接口。

image.png