关于equals和hushCode的重写!

mflk007 2011-09-25 10:29:31
代码如下:
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还是不想等..!!!求解
求改!!
...全文
56 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
huntor 2011-09-25
  • 打赏
  • 举报
回复
public boolean equals(Object another){
if(another == this) return true;
if(another instanceof MyDate){
MyDate that = (MyDate)another;
.... // compare field
}
return false; // ?
}
huntor 2011-09-25
  • 打赏
  • 举报
回复
equals的参数是 Object
mflk007 2011-09-25
  • 打赏
  • 举报
回复
后面写错了 是hashCode....为啥改完之后 equals还是不相等啊!

50,549

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧