A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© xuchulong1 中级黑马   /  2012-10-29 23:02  /  1349 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

这里定义一个点(是张老师视频里的)
public class ReflectPoint
{
@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;
}


private int x;
public int y;

public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
}



这是一个测试类
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;


public class Test2 {


public static void main(String[] args)
{
Collection c = new HashSet();
ReflectPoint p1 = new ReflectPoint(3,3);
ReflectPoint p2 = new ReflectPoint(3,5);
ReflectPoint p3 = new ReflectPoint(3,3);

c.add(p1);
c.add(p2);
c.add(p3);
c.add(p1);
System.out.println(c.contains(p2));
System.out.println(c.contains(new ReflectPoint(3,5)));
p2.y = 10;
System.out.println(c.contains(p2));
System.out.println(c.contains(new ReflectPoint(3,5)));
System.out.println(c.contains(new ReflectPoint(3,10)));



c.remove(p2);
System.out.println(c.size());
}
}


输出结果是:
true
true
false
false
false
2
我的问题是党我们添加了这个语句后 : p2.y = 10;   意味着我们修改了p2  但是为什么
System.out.println(c.contains(p2));
System.out.println(c.contains(new ReflectPoint(3,5)));
System.out.println(c.contains(new ReflectPoint(3,10)));
这三个都是fase呢?哈希表里面即没有了修改前的(3,5)  也没有修改后的(3,10),但是它里面却还是有 2 个数据,不得其解。

























评分

参与人数 1技术分 +1 收起 理由
尤圣回 + 1

查看全部评分

2 个回复

倒序浏览
那是由于:1.重写了的hashCode方法中用到了y变量的值:
          2.改变了y的值的话对象的hashCode值就变了,
          3.contains方法用到了hashCode,现在你知道为什么结果都为false了吧.

评分

参与人数 1技术分 +1 收起 理由
尤圣回 + 1

查看全部评分

回复 使用道具 举报
xuchulong1 来自手机 中级黑马 2012-10-30 00:06:10
藤椅
陈小红 发表于 2012-10-29 23:54
那是由于:1.重写了的hashCode方法中用到了y变量的值:
          2.改变了y的值的话对象的hashCode值就变 ...

我上面的点类中已经重载equals方法,只要数字相等,hashcode就相等,所以可以证明(3,5)(3,10)都不在表里,表里原来那个数字怎么会变成这两个点以外的元素,真心希望你能请问题并了解我上面那两个true的意图
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马