一、在讲解hashCode之前先说下ArrayList和HashSet的区别
看以下例子:
class PointR{
public PointR(int x, int y){
this.x=x;
this.y=y;
}
private int x;
private int y;
/*@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
}
PointR p1 = new PointR(3,3);
PointR p2 = new PointR(5,5);
PointR p3 = new PointR(3,3);
Collection collection = new ArrayList();
collection.add(p1);
collection.add(p2);
collection.add(p3);
collection.add(p1);
System.out.println(collection.size());
System.out.println("==============================");
Collection collection2 = new HashSet();
collection2.add(p1);
collection2.add(p2);
collection2.add(p3);
collection2.add(p1);
System.out.println(collection2.size());
结果为:
4
==============================
3
区别:
List里面是可以放重复元素的,并且是有序的
Set里面是不能存放相同的元素,并且是无序的
二、讲解hashCode
接着上面的例子,我们把PointR类的hashcode方法和euqals方法重写下
class PointR{
public PointR(int x, int y){
this.x=x;
this.y=y;
}
private int x;
private int 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;
PointR other = (PointR) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
}
PointR p1 = new PointR(3,3);
PointR p2 = new PointR(5,5);
PointR p3 = new PointR(3,3);
Collection collection = new ArrayList();
collection.add(p1);
collection.add(p2);
collection.add(p3);
collection.add(p1);
System.out.println(collection.size());
System.out.println("==============================");
Collection collection2 = new HashSet();
collection2.add(p1);
collection2.add(p2);
collection2.add(p3);
collection2.add(p1);
System.out.println(collection2.size());
结果为:
4
==============================
2
实现类的hashCode()方法,
单一个set容器去接受这个类的对象时,会根据hashCode算出来的值给这个对象分配一个区域,以后查找这个对象的时候就到这个区域里面去查找。
如果程序在运行的过程中:修改了参与hashCode的字段的值,这个时候如果调用remove去移除这个对象的时候,hashcode会根据现有成员变量的值算出区域,在区域里面查找并移除,这样找不到原有的对象了。这样就会造成内存溢出