这里定义一个点(是张老师视频里的)
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 个数据,不得其解。
|