标签:name HashSet int 练习 MyDate month birthday Employee
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);
}
}
标签:name,HashSet,int,练习,MyDate,month,birthday,Employee 来源: https://www.cnblogs.com/coderDreams/p/15939079.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。