Java~当HashMap中key为对象时为何要重写hashCode和equals

文章目录

HashMap存储结构

  • HashMap是以键值对的形式进行存储, 其内部是一个数组+单链表+红黑树的存储方式, 在put新增数据的时候首先要使用HashCode得到其哈希值, 然后在使用哈希函数散列到数组中的具体的一个位置, 然后遍历单链表, 如果key相同, 就覆盖value, 如果key不同就加在链表的尾部, 如果这个单链表的长度大于8并且数组长度大于64, 就将这个链表扩容成红黑树
  • 好, 那我们有这样一个需求, HashMap中key是new的一个对象,我们观察下面代码
public class Test {

    public static void main(String[] args) {
        //构建三个person, 其中person和person2从表面看应该是相同的
        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, "第二名");
        //获取person2
        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 && // 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;
    }
  • 好, 那我们再重写person的equals方法
        @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);
        }
  • 最后进行测试
    在这里插入图片描述
  • 输出为第一名
  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值