HashMap存储结构
- HashMap是以键值对的形式进行存储, 其内部是一个数组+单链表+红黑树的存储方式, 在put新增数据的时候首先要使用HashCode得到其哈希值, 然后在使用哈希函数散列到数组中的具体的一个位置, 然后遍历单链表, 如果key相同, 就覆盖value, 如果key不同就加在链表的尾部, 如果这个单链表的长度大于8并且数组长度大于64, 就将这个链表扩容成红黑树
- 好, 那我们有这样一个需求, HashMap中key是new的一个对象,我们观察下面代码
public class Test {
public static void main(String[] args) {
Person person = new Person("Listen", 22);
Person person1 = new Person("bike", 21);
Person person2 = new Person("Listen", 22);
Map<Person, String> map = new HashMap<>();
map.put(person, "第一名");
map.put(person1, "第二名");
System.out.println(map.get(person2));
}
static class Person {
public String name;
public int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
}
- 从表面看或者从属性字段看, person和person2应该是相同的一个人, 输出的应该是"第一名", 但是实际并不是如此

- 其原因就是因为在HashMap存储的时候, 首先会得到其hash值, 而默认的获取hash值的方法是native的, 也就是获取的是物理层面的, 其实获取的是其存储地址
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
public native int hashCode();
- 这时我们就发现, 由于person和person2都是分别new的对象, 所以其物理地址自然不同, 所以其hash值自然不同, 所以就找不到输出为null
- 那我们重写Person到的hashCode方法
static class Person {
public String name;
public int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
- 此时我们获取hash值的方式就是获取其属性字段的hash值, 如果属性字段相同那么hash值自然相同
- 但是此时运行main输出还时null, 我们查看get方法, 会发现, 即使我们person2到达了正确的单链表上, 但是对单链表进行遍历, 判断key是否相同的时候, 使用的是equals进行, 判断的, 而equals如果不重写, 其默认还是使用==进行物理地址的判断相等
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 &&
((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;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age == person.age &&
name.equals(((Person) o).name);
}
- 最后进行测试

- 输出为第一名