package Gather.CollectionArrayList.HashSet;
import java.util.HashSet;
import java.util.Objects;
/**
* @author 小王宝友
* @version 3.89
*/
@SuppressWarnings({"all"})
public class HashSetExercise2 {
public static void main(String[] args) {
HashSet set = new HashSet();
set.add(new Emm("Tom",18,new MyDate(2003,8,9)));
set.add(new Emm("Tom",18,new MyDate(2004,8,9)));
set.add(new Emm("Tom",18,new MyDate(2003,8,9)));
System.out.println("HashSet="+set);
}
}
class Emm extends MyDate{
private String name;
private int age;
private MyDate birthday;
public Emm(String name, int age,MyDate birthday) {
this.name = name;
this.age = age;
this.birthday=birthday;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Emm e = (Emm) o;
return Objects.equals(name, e.name) && Objects.equals(birthday, e.birthday);
}
@Override
public int hashCode() {
return Objects.hash(name, birthday);
}
@Override
public String toString() {
return "Emm{" +
"name='" + name + '\'' +
", age=" + age +
", birthday=" + birthday +
'}';
}
}
class MyDate{
private int year;
private int month;
private int day;
public MyDate() {
}
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 +
'}';
}
@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);
}
}
【JAVASE】HashSet的hashCode、equals重写
最新推荐文章于 2022-07-30 16:05:56 发布