在实际使用中如果遇到对象作为HashMap结构的key,则一定要注意重写equals和hashCode两个方法。以JDK8为例,HashMap在put(K key, V value)方法和containsKey(Object key)方法都会进行当前HashMap中是否已有待放入的key,比如containsKey(Object key)方法:
/**
* Returns <tt>true</tt> if this map contains a mapping for the
* specified key.
*
* @param key The key whose presence in this map is to be tested
* @return <tt>true</tt> if this map contains a mapping for the specified
* key.
*/
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
/**
* Computes key.hashCode() and spreads (XORs) higher bits of hash
* to lower. Because the table uses power-of-two masking, sets of
* hashes that vary only in bits above the current mask will
* always collide. (Among known examples are sets of Float keys
* holding consecutive whole numbers in small tables.) So we
* apply a transform that spreads the impact of higher bits
* downward. There is a tradeoff between speed, utility, and
* quality of bit-spreading. Because many common sets of hashes
* are already reasonably distributed (so don't benefit from
* spreading), and because we use trees to handle large sets of
* collisions in bins, we just XOR some shifted bits in the
* cheapest possible way to reduce systematic lossage, as well as
* to incorporate impact of the highest bits that would otherwise
* never be used in index calculations because of table bounds.
*/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
/**
* Implements Map.get and related methods
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
可以看到,在判断当前Map中是否有要查询的Object key时,先进入混淆函数hash(Object key)计算得出对应的hash值,再根据hash值和equals()函数结果判断是否有当前key。所以,尤其在自定义对象作为key的时候,一定要覆盖equals和hashCode两个方法,equals方法容易实现,hashCode方法就需要开发人员合理地设计了,因为要遵循两个对象equals为true,那么这两个对象中的每个对象调用 hashCode
方法都必须生成相同的整数结果。
测试代码:
给学生发学生卡,每个学生对应一个唯一的学号
/**
* @author lingyingqiaoren
* @since 2019-08-02
*/
public class Student {
/**
* 学号
*/
private Integer id;
/**
* 姓名
*/
private String name;
public Student() {
}
public Student(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return this.id;
}
@Override
public String toString(){
return "Student{id:" + this.id + ";name:" + this.name + "}";
}
@Override
public boolean equals(Object o){
return this.id.equals(((Student) o).getId());
}
@Override
public int hashCode(){
return this.id;
}
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
Student xiaoMing = new Student(1,"小明");
//故意把小亮学号设成小明的,作为异常数据,不应该发给他学生卡
Student xiaoLiang = new Student(1,"小亮");
students.add(xiaoMing);
students.add(xiaoLiang);
Map<Student, SchoolCard> match = new HashMap<>(16);
students.stream().forEach(
student -> {
if (!match.containsKey(student)) {
match.put(student, new SchoolCard());
}
}
);
System.out.println(match);
}
}
程序运行输出结果:
{Student{id:1;name:小明}=SchoolCard@4f3f5b24}
如果注释掉Student类中equals和hashCode两个方法中的任意一个,程序就会输出如下:
{Student{id:1;name:小亮}=SchoolCard@7b23ec81, Student{id:1;name:小明}=SchoolCard@6acbcfc0}