hashCode 作用,对象根据hashCode的值分区域存放
/** * hashCode 作用 * * @author Administrator * */ public class Point { public static void main(String[] args) { Point p1 = new Point(3, 3); Point p2 = new Point(2, 3); Point p3 = new Point(3, 3); HashSet<Point> set = new HashSet<>(); set.add(p1); set.add(p2); set.add(p3); set.add(p1); p1.x = 7; // 修改equals 中的变量的值,hashCode改变,查找的hash区域变化,在新计算的区域p1无法找到,无法删除,最后可能引起内存泄漏 set.remove(p1); System.out.println(set.size()); } int x; int y; public Point(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; Point other = (Point) obj; if (x != other.x) return false; if (y != other.y) return false; return true; } }
原文地址:https://www.cnblogs.com/newlangwen/p/9650392.html
时间: 2024-11-11 07:04:28