首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

【转】JAVA中重写equals()步骤为什么要重写hashcode()方法说明【三】

2013-08-01 
【转】JAVA中重写equals()方法为什么要重写hashcode()方法说明【三】public class Cat {private String namep

【转】JAVA中重写equals()方法为什么要重写hashcode()方法说明【三】
public class Cat {private String name;private String birthday;public Cat(){}public void setName(String name){this.name = name;}public String getName(){return name;}public void setBirthday(String birthday){this.birthday = birthday;}public String getBirthday(){return birthday;} //重写equals方法public boolean equals(Object other){if(this == other){//如果引用地址相同,即引用的是同一个对象,就返回truereturn true;} //如果other不是Cat类的实例,返回falseif(!(other instanceOf Cat)){return false;}final Cat cat = (Cat)other; //name值不同,返回falseif(!getName().equals(cat.getName())return false; //birthday值不同,返回falseif(!getBirthday().equals(cat.getBirthday()))return false;return true;} //重写hashCode()方法public int hashCode(){int result = getName().hashCode();result = 29 * result + getBirthday().hashCode();return result;}}

?

重写父类方法的原则:可以重写方法的实现内容,成员的存取权限(只能扩大,不能缩小),或是成员的返回值类型(但此时子类的返回值类型必须是父类返回值类型的子类型)。

?

热点排行