public class HasCod2 {
private int x;
private int y;
public HasCod2(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;
HasCod2 other = (HasCod2) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
public static void main(String[] args) throws Exception {
Collection coll=new HashSet();
HasCod2 hc1=new HasCod2(3,3);
HasCod2 hc2=new HasCod2(2,4);
HasCod2 hc3=new HasCod2(3,3);
coll.add(hc1);
coll.add(hc2);
coll.add(hc3);
coll.add(hc1);
hc1.x=8;
coll.remove(hc1);
System.out.print(coll.size());
}
}张老师说,当你修改hc1指向的对象的x值时,hc1的hashcode值又存在了另一个区域中,你删hc1的时候他找不到原来的hc1,所以打印结果是2.我想问的是:你既然修改了hc1的x值,那hc1自然也就会指向这个新的对象,他要删除,也只能找修改后的新区域的元素,怎么还会去找原来区域中的元素删呢?不知大家是怎么理解的
|