关于equals和hushCode的重写!
代码如下:
package pk1;
public class TestDate
{
public static void main(String [] args)
{
MyDate myDate = new MyDate();
myDate.setDate(25, 9, 2011);
myDate.getDate();
MyDate yourDate = new MyDate();
yourDate.setDate(25, 9, 2011);
yourDate.getDate();
if(yourDate.equals(myDate))
{
System.out.println("两个对象相等!");
}
else
System.out.println("不相等!");
System.out.println(myDate.hashCode());
System.out.println(yourDate.hashCode());
}
}
class MyDate
{
private int day;
private int month;
private int year;
public void setDate(int day,int month,int year)
{
if(isTrueDate(day,month,year))
{
this.day = day;
this.month = month;
this.year = year;
}
else
System.out.println("日期设置错误,请重新检查");
}
private boolean isTrueDate(int day,int month,int year)
{
int DateArray[][]={{31,28,31,30,31,30,31,31,30,31,30,31},
{31,29,31,30,31,30,31,31,30,31,30,31}};
if (day>0 && day<=31)
{
if(month>0 && month<=12)
{
if( year>0)
{
if( isLeapYear(year))
{
if(day<=DateArray[1][month-1])
{
return true;
}
else
{
System.out.println(year+"是闰年"+month+"月-----没有"+day+"日");
return false;
}
}
else
{
if(day<=DateArray[0][month-1])
{
return true;
}
else
{
System.out.println(year+"年"+month+"月-----没有"+day+"日");
return false;
}
}
}
else
{
System.out.println("年份必须大于零!");
return false;
}
}
else
{
System.out.println("日期中-----没有"+month+"月");
return false;
}
}
else
{
System.out.println("日期中-----没有"+day+"天");
return false;
}
}
private boolean isLeapYear(int year)
{
if((year%4==0 && year%100!=0)|| year%400==0)
{
return true;
}
else
return false;
}
public void getDate()
{
System.out.println(year+"年"+month+"月"+day+"日\n");
}
public boolean equals(MyDate obj)
{
if(this.day==obj.day && this.month==obj.month && this.year==obj.month)
return true;
else
return false;
}
public int hashCode()
{
int result = 0;
result=this.day; //result = this.day + this.month*100 + this.year*10000;
return result;
}
}
按我那个重写的hushCode不是已经覆盖了原来的hash么...返回的hashCode一样可是equals还是不想等..!!!求解
求改!!
------解决方案--------------------
equals的参数是 Object
------解决方案--------------------
Java code
public boolean equals(Object another){
if(another == this) return true;
if(another instanceof MyDate){
MyDate that = (MyDate)another;
.... // compare field
}
return false; // ?
}