hashCode()作用
按照先例,先上段代码:
public class Person {
public String name;
public int age;
public Person(String n, int a){
this.name = n;
this.age = a;
}
}
Collection collection = new ArrayList<>();
collection.add(new Person("111",1));
collection.add(new Person("222",2));
collection.add(new Person("333",3));
collection.add(new Person("111",1));
System.out.println(collection.size());
结果为4,然后我们把ArrayList改为HashSet,结果还是为4。
接着,我们覆盖Person类中的hashCode().
public class Person {
public String name;
public int age;
public Person(String n, int a){
this.name = n;
this.age = a;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
Collection collection = new HashSet<>();
collection.add(new Person("111",1));
collection.add(new Person("222",2));
collection.add(new Person("333",3));
collection.add(new Person("111",1));
System.out.println(collection.size());
结果竟然神奇地变为3。
出现这一结果的原因就在于 Person中的hashCode()方法。
在搞清楚这个原因之前,我们还是先了解下HashSet的工作原理
HashSet
HashSet是采用哈希算法存取对象的集合,它内部采用对某个数字n进行取余的方式对哈希码进行分组和划分对象的存储区域。Object类中定义了一个hashCode()方法来返回每个java对象的哈希码,然后根据哈希码找到对应的存储区域,最后取出该存储区域内的每个元素与该对象进行 equals方法比较,这样不用遍历集合中的所有元素。因此,HashSet集合具有很好的对象检索性能,但同时,它存储对象的效率要低些,因为在添加对象时,要先算出对象的哈希码和根据这个哈希码来确定对象在集合中的存放位置。
原因解析
通过以上描述,我们知道了HashSet不同于ArrayList,它是通过存入对象的HashCode来判断对象的唯一性,如果哈希码相等的两个对象,在HashSet中仅存一份。
需要注意的是,如果我们没有覆盖Person中的hashCode(),那么HashSet就会默认通过Person的超类Object中的hashCode()方法来算出哈希码,Object中的hashCode()又是通过对象在内存中的地址来判断的,因此new Person(“111”,1)跟new Person(“111”,1)算出的哈希码是不同的。只有覆盖了hashCode(),这两者的哈希值才会相同,因为覆盖后的hashCode()是通过 name跟age字段来确定的。
内存泄露风险
Collection collection = new HashSet<>();
Person p1 = new Person("111",1);
Person p2 = new Person("222",2);
Person p3 = new Person("333",3);
Person p4 = new Person("111",1);
collection.add(p1);
collection.add(p2);
collection.add(p3);
collection.add(p4);
collection.remove(p1);
结果与预期的一样为2,p1被成功的移除了。
但改写一下:
Collection collection = new HashSet<>();
Person p1 = new Person("111",1);
Person p2 = new Person("222",2);
Person p3 = new Person("333",3);
Person p4 = new Person("111",1);
collection.add(p1);
collection.add(p2);
collection.add(p3);
collection.add(p4);
p1.name="aaa";
collection.remove(p1);
结果却不是我们想的那样是2,而是3.说明p1没有成功移除,这又是为什么呢?因为我们改变了name的值,前面说过,Person的哈希码跟name和age有关,改变了name的值,哈希码自然也改变了,因此p1跟原来的p1在HashSet中并非同一份,这时就移除不了之前的p1了,造成了内存泄露。
注意事项
为了保证一个类的实力对象能在HashSet中正常存储,要求这个类的两个实力对象在equals()方法比较的结果相等时,他们的哈希码也必须相等。