Why does not implement the equals method in Java cause a memory leak

I am trying to understand the various causes of a memory leak with one of the patterns that I saw where hashCode () was implemented, not equals (). I read that if someone moves, the other should also be forwarded due to breach of contract.

this is 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 that I did not use the equals () method specifically. But I want to understand why a memory leak occurs, what happens inside.

thanks

+6
source share
1 answer

If you do not implement Key#equals() , no two instances of Key will be equal, so Map#containsKey() will always return false . In addition, you check containsKey(i) , but do not use i as a key. Even if you implemented Key#equals() , this containsKey check is effective if(true) .

Therefore, this code unconditionally adds logically different entries to the card, so its size grows without restrictions.

+11
source

Source: https://habr.com/ru/post/955578/


All Articles