简体   繁体   中英

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(). 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. 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 . Additionally, you're checking containsKey(i) , but not using i as a key. Even if you did implement Key#equals() , that containsKey check is effectively if(true) .

Consequently, this code unconditionally adds logically-distinct entries to the map, so its size grows without bound.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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