- public static void main(String[] args) {
- // TODO Auto-generated method stub
-
- //Collection collections = new ArrayList(); //size为4
- Collection collections = new HashSet(); //size为3
-
- ReflectPoint pt1 = new ReflectPoint(3,3);
- ReflectPoint pt2 = new ReflectPoint(5,5);
- ReflectPoint pt3 = new ReflectPoint(3,3);
-
- collections.add(pt1);
- collections.add(pt2);
- collections.add(pt3);
- collections.add(pt1); //有相同对象,没存进去
-
- //System.out.println(collections.size()); //输出 3
- pt1.x=7; //这里改变字段,哈希值应该会变化,下面的移除造作无效,导致内存泄露
- collections.remove(pt1);
-
- System.out.println(collections.size()); // 输出2 上面移除无效,这里应该也输出3,但结果是输出2,说明上一布的移除操作成功了
- }
复制代码 ReflectPoint类代码- public class ReflectPoint {
- int x;
- int y;
-
- public ReflectPoint(int x, int y) {
- super();
- this.x = x;
- this.y = y;
- }
复制代码 后来发现,只有重写了hashCode() 方法后,对计算哈希值的字段改动才会造成内存泄露。- public class ReflectPoint {
- int x;
- int y;
-
- public ReflectPoint(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;
- ReflectPoint other = (ReflectPoint) obj;
- if (x != other.x)
- return false;
- if (y != other.y)
- return false;
- return true;
- }
-
- }
复制代码 |