Java高级编程day22【谷】

这篇博客主要介绍了Java高级编程中的TreeSet排序,包括自然排序和定制排序,并提供了Employee类和MyDate类的示例。同时,讲解了Map接口,特别是HashMap的底层实现原理,包括JDK7和JDK8的区别。还提到了TreeMap、properties以及Collections工具类的常用方法和应用场景。
摘要由CSDN通过智能技术生成

Java高级编程day22

Tree 自然排序与定制排序练习题

1.定义一个Employee类。
该类包含:private成员变量name,age,birthday,其中birthday为
MyDate类的对象;
并为每一个属性定义getter,setter方法南
并重写toString方法输出name,age,brthday.
MyDate类包含:
private成员变量year,month,day;并为每一个属性定义getter,setter
方法;
创建该类的5个对象,并把这些对象放入TreeSet集合中(下一章:
TreeSet需使用泛型来定义)
分别按以下两种方式对集合中的元素进行排序,并遍历输出:
1).使Employee实现Comparable接口,并按name排序,
2).创建TreeSet时传入Comparator对象,按生日日期的先后排序。

Employee类

public class Employee implements Comparable {
   
    private String name;
    private int age;
    private MyDate birthday;

    public Employee(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;
    }

    public MyDate getBirthday() {
   
        return birthday;
    }

    public void setBirthday(MyDate birthday) {
   
        this.birthday = birthday;
    }

    @Override
    public String toString() {
   
        return "Employee{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", birthday=" + birthday +
                '}';
    }

    @Override
    public boolean equals(Object o) {
   
        if (this == o) return true;
        if (!(o instanceof Employee)) return false;
        Employee employee = (Employee) o;
        return age == employee.age && Objects.equals(name, employee.name) && Objects.equals(birthday, employee.birthday);
    }

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

    @Override
    public int compareTo(Object o) {
   
        //使Employee实现Comparable接口,并按name排序
        if(o instanceof Employee){
   
            return ((Employee) o).getName().compareTo(this.name);
        }
        throw new RuntimeException("类型不匹配");
    }
}

MyData类

public class MyDate implements Comparable{
   
    private Integer year;
    private Integer month;
    private Integer day;

    public MyDate(int year, int month, int day) {
   
        this.year = year;
        this.month = month;
        this.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 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值