import java.util.HashSet; import java.util.Objects; @SuppressWarnings({"all"}) public class HashSetExercise02 { public static void main(String[] args) { /** * 定义一个Employee类,该类包含:private属性 : * name,sal,birthday(MyDate类型,需自己定义), * 其中 birthday 为 MyDate类型(属性包括:year,month,day),要求: * 1、创建3个Employee 放入 HashSet中 * 2、当 name 和 birthday 的值相同时,认为是相同员工,不能添加到HashSet集合中 */ HashSet hashSet = new HashSet(); hashSet.add(new Employee01("曾小贤", 100, new MyDate(2000, 1 ,1))); hashSet.add(new Employee01("曾小贤", 200, new MyDate(2000, 1 ,11))); hashSet.add(new Employee01("曾小贤", 100, new MyDate(2000, 1 ,1))); hashSet.add(new Employee01("胡一菲", 100, new MyDate(2000, 1 ,1))); for (Object o : hashSet) { System.out.println("o= " + o); } } } class Employee01 { private String name; private double sal; private MyDate birthday; public Employee01(String name, double sal, MyDate birthday) { this.name = name; this.sal = sal; this.birthday = birthday; } @Override public String toString() { return "Employee01{" + "name='" + name + '\'' + ", sal=" + sal + ", birthday=" + birthday + '}'; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getSal() { return sal; } public void setSal(double sal) { this.sal = sal; } public MyDate getBirthday() { return birthday; } public void setBirthday(MyDate birthday) { this.birthday = birthday; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Employee01 that = (Employee01) o; return Objects.equals(name, that.name) && Objects.equals(birthday, that.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 String toString() { return "MyDate{" + "year=" + year + ", month=" + month + ", day=" + day + '}'; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public int getMonth() { return month; } public void setMonth(int month) { this.month = month; } public int getDay() { return day; } public void setDay(int day) { 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); } }
java韩顺平HashSet课后练习2
最新推荐文章于 2024-04-10 23:03:59 发布