所謂記憶體洩露就是一個對象占用的一塊記憶體,當這個對象不在被使用時,該記憶體還沒有被收回。
例子
package cn.xy.test;
public class point2
{
private int x;
private int y;
public point2(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;
public boolean equals(object obj)
if (this == obj) return true;
if (obj == null) return false;
if (getclass() != obj.getclass()) return false;
point2 other = (point2) obj;
if (x != other.x) return false;
if (y != other.y) return false;
return true;
public int getx()
return x;
public void setx(int x)
public int gety()
return y;
public void sety(int y)
}
public class hashsetandhashcode2
public static void main(string[] args)
hashset<point2> hs2 = new hashset<point2>();
point2 p21 = new point2(3, 3);
point2 p22 = new point2(3, 5);
hs2.add(p21);
hs2.add(p22);
p22.sety(7);
hs2.remove(p22);
system.out.println(hs2.size());
很多人認為列印出的結果是1。結果是2。為什麼呢?當一個對象被存儲在hashset中後,如果修改參與計算hashcode有關的字段,那麼修改後的hashcode的值就與一開始存儲進來的hashcode的值不同了,這樣contains無法通過hashcode找到該元素,是以無法删除。這就告訴我們,當一個對象被存儲在hashset中後,不要修改與計算hashcode有關的字段。