实例的常见操作作业——比较日期大小

编写一个类MyDate 表示日期,它有三个int属性 year,month,date 表示年月日,不用做录入数据检 查,认为创建实例时录入的数据都是正确的。 实现以下实例的操作

(1) 如果两个MyDate实例的年月日值一致,认为两者“相等”

(2) 调用toString方法返回字符串日期格式: “1997-05-12”

(3) 提供MyDate实例的克隆方法

(4) 实现MyDate的比较规则,越未来的日期越大

public class MyDate implements Cloneable,Comparable<MyDate>{
    public int year,month,date;

    public MyDate(int year,int month,int date){
        this.year=year;
        this.month=month;
        this.date=date;
    }
    public boolean equals(Object obj){
        if (obj instanceof MyDate){
            MyDate temp=(MyDate) obj;
            return (this.year== temp.year&&
                    this.month==month&&this.date==date);
        }
        return false;
    }
    public String toString(){
        return "{"+this.year+"-"+this.month+"-"+this.date+"}";
    }
    public int hashcode(){
        return this.year;
    }

    public Object clone() throws CloneNotSupportedException{
        return new MyDate(year,month,date);
    }

    @Override
    public int compareTo(MyDate o) {
        if(this.year>o.year){
            return 1;
        } else if (this.year<o.year) {
            return -1;
        }else if (this.month>o.month){
            return 1;
        }else if(this.month<o.month){
            return -1;
        } else if (this.date>o.date) {
            return 1;
        }else if (this.date<o.date){
            return -1;
        }


        return 0;
    }
}

public class Test1 {
    public static void main(String[] args) throws CloneNotSupportedException {
        MyDate d1=new MyDate(1997,01,07);
        MyDate d2=new MyDate(1997,01,07);
        MyDate[] da=new MyDate[3];
        da[0]=new MyDate(1997,01,07);
        da[1]=new MyDate(1997,04,07);
        da[2]=new MyDate(1997,04,07);


        System.out.println(d1==d2);

        MyDate d3=(MyDate) d1.clone();
        System.out.println(d3);


        System.out.println(da[0].compareTo(da[1]));
        System.out.println(da[2].compareTo(da[1]));
        System.out.println(da[1].compareTo(da[0]));



    }
}

     

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值