java hashCode 作用
阿新 • • 發佈:2018-09-15
ring min code equals obj bool spa rri other
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; returnresult; } @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; } }
java hashCode 作用