编写一个类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]));
}
}