Hash存储与内存泄漏
public class Point { private int x; private int y; public Point(int x, int y) { 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; Point other = (Point) 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) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } }
public class Test { public static void main(String[] args) { Collection<Point> aCol = new ArrayList<Point>(); Collection<Point> hCol = new HashSet<Point>(); Point a = new Point(1, 2); Point b = new Point(2, 2); Point c = new Point(1, 2); aCol.add(a); aCol.add(b); aCol.add(c); aCol.add(a); //重复添加a对象 hCol.add(a); hCol.add(b); hCol.add(c); hCol.add(a); //重复添加a对象 System.out.println(aCol.size()); //采用非hash存储,没有必要修改hashcode 和 equals方法 size不会变 System.out.println(hCol.size()); //前:3 后:2 (必须同时修改hashCode()和equals()) System.out.println("-----------------------"); methodTest(); } private static void methodTest() { Collection<Point> aCol = new ArrayList<Point>(); Collection<Point> hCol = new HashSet<Point>(); Point a = new Point(1, 2); Point b = new Point(2, 2); Point c = new Point(1, 2); aCol.add(a); aCol.add(b); aCol.add(c); aCol.add(a); //重复添加a对象 hCol.add(a); hCol.add(b); hCol.add(c); hCol.add(a); //重复添加a对象 b.setX(8); aCol.remove(b); hCol.remove(b); System.out.println(aCol.size()); System.out.println(hCol.size()); //前:1 后:2(修改了对象的参与hash值计算的属性值 结果会导致remove不到此对象) //了解Hash的存储方式 //上面总结下来就是一个内存泄漏的实例 } }