简体   繁体   English

为什么不在Java中实现equals方法导致内存泄漏

[英]why does not implementing equals method in Java cause memory leak

I am trying to understand various reasons for memory leak one of the samples i saw where hashCode() was implemented and not equals(). 我试图了解内存泄漏的各种原因我看到的样本中的hashCode()实现了而不是equals()。 I have read through that one if one is over ridden the other also has to be over ridden because of contract violation. 我已经读完了那个,如果一个人被过度骑行,另一个也因为违反合同而被过度骑行。

this is the sample code 这是示例代码

import java.util.HashMap;
import java.util.Map;

public class MemoryLeak {

static class Key { 
    Integer id; 

    Key(Integer id) { 
        this.id = id; 
    } 

    @Override 
    public int hashCode() { 
        return id.hashCode(); 
    }   
} 
public static void main(String[] args) {
    // TODO Auto-generated method stub

    Map m = new HashMap(); 
    while (true) 
        for (int i = 0; i < 10000; i++) 
            if (!m.containsKey(i)) 
                m.put(new Key(i), "Number:" + i); 
}
}

I know i have not implemented the equals() method on purpose. 我知道我没有故意实现equals()方法。 But i want to under stand why is memory leak is created what is going on internally. 但我想知道为什么会在内部发生内存泄漏。

thanks 谢谢

If you don't implement Key#equals() , no two Key instances will be equal, so Map#containsKey() will always return false . 如果没有实现Key#equals() ,则两个Key实例不会相等,因此Map#containsKey()将始终返回false Additionally, you're checking containsKey(i) , but not using i as a key. 此外,您正在检查containsKey(i) ,但不使用i作为键。 Even if you did implement Key#equals() , that containsKey check is effectively if(true) . 即使你确实实现了Key#equals() ,那么containsKey检查也是有效的if(true)

Consequently, this code unconditionally adds logically-distinct entries to the map, so its size grows without bound. 因此,此代码无条件地向地图添加逻辑上不同的条目,因此其大小不受限制地增长。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM