HashSet小练习
需求
- 定义一个Employee类
- 该类包含: private成员属性name,sal,birthday(MyDate类型)
- 其中 birthday为 MyDate类型(属性包括:year, month, day)
- 要求:
- 创建3个Employee 放入HashSet中
- 当name和birthday的值相同时,认为是相同员工,不能添加到HashSet集合中
代码
package com.collection.set.train;
import java.util.HashSet;
import java.util.Objects;
public class Demo {
public static void main(String[] args) {
MyDate birthday1 = new MyDate(2003, 1, 3);
MyDate birthday2 = new MyDate(2003, 1, 3);
Employee employee1 = new Employee("小王", 2000, birthday1);
Employee employee2 = new Employee("小王", 3000, birthday2);
HashSet<Employee> employees = new HashSet<>();
employees.add(employee1);
boolean add = employees.add(employee2);
System.out.println(add);
}
}
class Employee {
private String name;
private int sal;
private MyDate birthday;
public Employee(String name, int sal, MyDate birthday) {
this.name = name;
this.sal = sal;
this.birthday = birthday;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return Objects.equals(name, employee.name) && Objects.equals(birthday, employee.birthday);
}
@Override
public int hashCode() {
return Objects.hash(name, birthday);
}
}
class MyDate {
private int year;
private int month;
private int day;
public MyDate(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MyDate myDate = (MyDate) o;
return year == myDate.year && month == myDate.month && day == myDate.day;
}
@Override
public int hashCode() {
return Objects.hash(year, month, day);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!