其他分享
首页 > 其他分享> > HashSet小练习

HashSet小练习

作者:互联网

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