天天看点

Java中的HashCode(2)之Hashset造成的内存泄露

所谓内存泄露就是一个对象占用的一块内存,当这个对象不在被使用时,该内存还没有被收回。

例子

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有关的字段。