HashSet练习题

定义一个Employee类,该类包含:private成员属性name,salary,birthday(MyDate类型,属性包括:year,month,day),要求:

1、创建至少3个Employee放入Hash Set中;

2、当name和birthday的值相同时,认为是相同员工,不能添加到HashSet集合中。

package Ex02;

import java.util.HashSet;
import java.util.Objects;

public class Ex02 {
    public static void main(String[] args) {

        HashSet set01=new HashSet();
        Employee k007=new Employee("mus", 2543.4,new Employee.MyDate(1997,2,13));
        Employee k006=new Employee("sdj", 1274.2,new Employee.MyDate(1998,7,23));
        Employee k005=new Employee("fkr", 9543.8,new Employee.MyDate(1968,8,27));
        Employee k004=new Employee("loo", 4958.3,new Employee.MyDate(1789,4,3));
        Employee k003=new Employee("mus", 2543.4,new Employee.MyDate(1997,2,13));
        Employee k002=new Employee("mus", 2543.4,new Employee.MyDate(1998,2,29));
        Employee k001=new Employee("ssd", 2345.1,new Employee.MyDate(1968,8,27));

        set01.add(k001);
        set01.add(k002);
        set01.add(k003);
        set01.add(k004);
        set01.add(k005);
        set01.add(k006);
        set01.add(k007);

        System.out.println(set01);

    }
}

class Employee{
    private String name;
    private double salary;
    private MyDate myDate;

    public Employee(String name, double salary, MyDate myDate) {
        this.name = name;
        this.salary = salary;
        this.myDate = myDate;
    }

    static class MyDate{
        int year;
        int month;
        int day;

        public MyDate(int year, int month, int day) {
            this.year = year;
            this.month = month;
            this.day = day;
        }

        @Override
        public String toString() {
            return "Date:" + year +
                    "-" + month +
                    "-" + day;
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee employee = (Employee) o;

        return Double.compare(salary, employee.salary) == 0 && Objects.equals(name, employee.name) &&employee.myDate.year == myDate.year && employee.myDate.month == myDate.month && employee.myDate.day == myDate.day;

    }

    @Override
    public int hashCode() {
        return Objects.hash(name, salary);
    }

    @Override
    public String toString() {
        return name + ',' +
                + salary +
                "," + myDate +
                '}'+"\n";
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值