hashCode 作用,对象根据hashCode的值分区域存放
/**
* hashCode 作用
*
* @author Administrator
*
*/
public class Point { public static void main(String[] args) {
Point p1 = new Point(, );
Point p2 = new Point(, );
Point p3 = new Point(, ); HashSet<Point> set = new HashSet<>(); set.add(p1);
set.add(p2);
set.add(p3);
set.add(p1);
p1.x = ;
// 修改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 = ;
int result = ;
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;
} }