bhxiaobo 发表于 2012-10-31 10:25
这个和hashCode值有关系,如果你自己写一个Point 类,然后覆盖它的hashcode方法,如果你用基本数据类型的话 ...
应该是这样的我重写equals重新试了一下,的确如此
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 String str1 = "hellojava";
public String str2 = "jakdbbbbbizad";
public String str3 = "hahahaha";
*/
public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
public String toString()
{
return x+" : "+y ;
}
}
测试类
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);
System.out.println(p1.hashCode());
System.out.println(p2.hashCode());
Iterator it = c.iterator();
while(it.hasNext())
{
System.out.println(it.next()+" hashcode:");
}
System.out.println(p2.hashCode());
p2.y = 10;
Iterator it1 = c.iterator();
while(it1.hasNext())
{
System.out.println(it1.next()+" hashcode:");
}
System.out.println(p1.hashCode());
System.out.println(p2.hashCode());
c.remove(p2);
System.out.println(c.size());
}
}
打印结果为:
1057
1059
3 : 5
3 : 3
1059
3 : 10
3 : 3
1057
1064
2
可见P2值改变了以后,hash表里的值也跟着改变了。但是移除的时候就不能移除了,这里会有内存的泄漏,这里我想打印hashset中存放的原来的p2的值的hashcode却不知道怎么打印了,还希望帮下忙哈
|