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
MyDate birthday1 = new MyDate(2003, 1, 3);
MyDate birthday2 = new MyDate(2003, 1, 3);
// 实例化两个相同name和birthday的Employee
Employee employee1 = new Employee("小王", 2000, birthday1);
Employee employee2 = new Employee("小王", 3000, birthday2);
// 重写相应的hashCode和equals
// System.out.println(employee1.hashCode() == employee2.hashCode());
// System.out.println(employee1.equals(employee2));
// 此时上方输出都为true
// 实例化一个HashSet
HashSet<Employee> employees = new HashSet<>();
employees.add(employee1);
boolean add = employees.add(employee2);
// 打印查看是否添加成功
System.out.println(add);
}
}
// 定义Employee类
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);
}
}
// 定义MyDate类
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;
}
// 重写hashCode
@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);
}
}