因未重写hashCode和equals方法导致的HashMap的内存泄漏问题

24 篇文章 0 订阅
5 篇文章 0 订阅

一、⭐⭐⭐何为内存泄漏🌙🌙🌙
内存泄漏,指的是该对象在Java应用程序中的使命已经完结,该做的事情都已经做完了,对Java应用程序来说,已经没有继续存在的价值和意义了,可以被GC回收了。可偏偏GC无法对这个对象做回收处理。因为,该对象被错误的禁锢在了某个不知名不易被察觉的地方。
随着时间的流逝,这种因各种原因导致的内存泄漏而存在的无效对象会越来愈多,占用的内存就越大,就有可能会导致Java应用程序申请不到足够的内存空间,引发内存溢出。
二、⭐⭐⭐Object中的hashCode和equals方法,注意注释🌙🌙🌙

/*
*	 Whenever it is invoked on the same object more than once during
*     an execution of a Java application, the {@code hashCode} method
*     must consistently return the same integer, provided no information
*     used in {@code equals} comparisons on the object is modified.
*     This integer need not remain consistent from one execution of an
*     application to another execution of the same application.
*    If two objects are equal according to the {@code equals(Object)}
*     method, then calling the {@code hashCode} method on each of
*     the two objects must produce the same integer result.
*    It is <em>not</em> required that if two objects are unequal
*     according to the {@link java.lang.Object#equals(java.lang.Object)}
*     method, then calling the {@code hashCode} method on each of the
*     two objects must produce distinct integer results.  However, the
*     programmer should be aware that producing distinct integer results
*     for unequal objects may improve the performance of hash tables
翻译:
每当在Java应用程序执行期间在同一对象上多次调用hashCode方法时,hashCode方法必须一致地返回相同的整数,前提是对象上的等号比较中使用的信息没有被修改。
这个整数不需要从应用程序的一次执行到同一应用程序的另一次执行保持一致。
如果根据equals(Object)方法两个对象相等,那么对两个对象的每个对象调用hashCode方法必须产生相同的整数结果。
根据java.lang.Object#equals(java.lang.Object)方法,如果两个对象不相等,则调用这两个对象中的每个对象的hashCode方法必须产生不同的整数结果。
但是,程序员应该意识到,为不同的对象产生不同的整数结果可能会提高散列表的性能
*/
public native int hashCode();
//Objec的equals方法直接对比的是两个对象的地址
public boolean equals(Object obj) {
   return (this == obj);
}

三、⭐⭐⭐HashMap在put方法里使用hashCode和equals方法🌙🌙🌙
可以看出,若key对应的类:
(1)只重写了equals没重写hashCode或hashCode和equals方法都没有重写,则new出来的两个key对应的类的对象即便属性完全相同,也会被HashMap的put方法判定为两个不同的元素(不同索引位置上的两个不同的元素),从而走到//(1),被作为新元素,都添加到HashMap中,而非更新key对应的value值。
(2)只重写了hashCode没重写equals,则new出来的两个key对应的类的对象即便属性完全相同,也会被HashMap的put方法判定为两个不同的元素(同一个索引位置上的链表上的两个不同的元素),从而走到//(2),被作为新元素,都添加到HashMap中,而非更新key对应的value值。
(3)重写了hashCode和equals,则new出来的两个key对应的类的对象如何属性完全相同,则会被HashMap的put方法判定为一个相同的元素,会走到//(3),更新key对应的value值。

public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {//注:这里的hash其实也是由key计算得到的。详见上面的put方法传参
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);//(1)
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);//(2)
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key//(3)
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dylanioucn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值