黑马程序员技术交流社区
标题:
关于hashCode方法和hashSet集合的问题
[打印本页]
作者:
crazy_primitive
时间:
2013-7-18 00:00
标题:
关于hashCode方法和hashSet集合的问题
本帖最后由 crazy_primitive 于 2013-7-18 13:14 编辑
public class ReflectTest {
public static void main(String[] args) {
Collection collections = new HashSet();
ReflectPoint rpt1 = new ReflectPoint(4,5);
ReflectPoint rpt2 = new ReflectPoint(7,2);
ReflectPoint rpt3 = new ReflectPoint(4,5);
collections.add(rpt1);
collections.add(rpt2);
collections.add(rpt3);
collections.add(rpt1);
System.out.println(collections.size());
}
}
public class ReflectPoint {
private int x;
public int y;
public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
/* @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ReflectPoint other = (ReflectPoint) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
}
//将hashCode()方法注释掉之前,System.out.println(collections.size())打印的是2
//,这个好理解,可为什么注释掉之后打印的是3呢?
复制代码
作者:
zms2100
时间:
2013-7-18 00:43
本帖最后由 zms2100 于 2013-7-18 00:45 编辑
1、因为一个很小细节的原因,注释复写的hashCode()方法后,添加元素到HashSet中时调用的还是hashCode方法不过是继承自Object的父类方法; (在equals复写方法首行添加个打印语句就会发现,复写的equals方法没被调用过)。
2、要用equals比较就将复写的hashCode方法定义为return XXX(int型数值);3、另外: equals方法中的第一个判断if(this==obj)这个也是多余,==比较的是内存地址值,而rpt1与rpt3虽然相同,但是是不同对象,所以内存地址值也肯定不相同。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2