【JAVASE】HashSet的hashCode、equals重写

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);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值