读书人

求大神答题啊感谢了

发布时间: 2013-04-21 21:18:07 作者: rapoo

求大神解题啊!!!!!!!!!感谢了
import java.util.Date;

//重写equals()与hashCode()方法的实例,可以根据对象中真正包括的域成员来比较两个对象是否相等。
public class Cat
{
private String name;
private Date birthday;


public Cat() {
}

public void setName(String name) {this.name = name;}
public String getName() {return name;}


public void setBirthday (Date birthday) {this.birthday = birthday;}
public Date getBirthday() {return birthday;}

public boolean equals(Object other) {
if(this == other)
return true;

if(!(other instanceof Cat))
return false;

final Cat cat = (Cat) other;

if(!getName().equals(cat.getName()))
return false;

if(!getBirthday().equals(cat.getBirthday()))
return false;

return true;
}

public int hashCode() {
int result = getName().hashCode();
result = 29*result + getBirthday().hashCode();
return result;
}
怎么写一个main()方法来运行这个类


public class Cat {

public static void main(String[] args) {
Date d = new Date();
Cat bigC = new Cat("BigCat", d);
Cat smallC = new Cat("BigCat", d);

System.out.println(bigC == smallC); // 1
System.out.println(bigC.equals(smallC)); // 2

Set<Cat> set = new HashSet<Cat>(); // 3
set.add(bigC);
set.add(smallC);
System.out.println(set.size());
}


这里三个部分:
1、==比较两个cat的地址,两个对象当然返回的false;
2、如果不覆盖equal的话,和==一样的效果,覆盖后,就可以自定义比较内容,这里是比较两个属性,所以返回true。
3、hashcode()是专门用来hash算法的,例如hashMap、hashSet等。此处用hashSet来举例,先会hash定位,定位后再比较equal,如果hashCode()不重写,相等的对象就不能定位在一块了,就会认为是两个不相等的对象。 楼主复写了hashCode后,两个相同的对象add入HashSet,size只有一个,证明两者hashCode相等且equal相等。
[解决办法]
引用:
引用:

楼主,你先得知道为什么要复写equal和hashcode,给你举个例子



Java code?123456789101112131415public class Cat { public static void main(String[] args) { Date d = new D……


+1
正解!建议楼主先明白为什么重写equals方法时要重写hashCode的方法,着重理解容器...

读书人网 >J2SE开发

热点推荐