Title: Infinite loop when using a key multiple times in HashMap
Tags: java;hash;hashmap;stack-overflow
Question: ```HashMap``` falls into an infinite loop.

I am not able to understand why ```HashMap``` throws stackoverflow error when the same key is used multiple times.

Code:

```import java.util.HashMap;

public class Test {
    public static void main(String[] args) {
        HashMap hm = new HashMap();

        hm.put(hm, "1");
        hm.put(hm, "2");
    }
} 
```

Error:

```
  Exception in thread "main" java.lang.StackOverflowError 
```

Comment: You can't use key as its own object

Comment: Yeah, that's fine but why stack overflow...:(

Comment: thanks , as from java docs it has been cleared.

Comment: dont use raw types with HashMap

Comment: And don't use mutable types as hash map keys.

Comment: You use the map itself as a key??

Comment: Can you post the full stacktrace? I think there are hints on why it cause the stack overflow.

Comment: if you dig a little in the code of the `put` method, and if you look at the stacktrace, you'll find that the key depends on the keys.

Here is the accepted answer: It is not possible to add to a ```Map``` itself as a key. From javadoc:

```
  A special case of this prohibition is that it is not permissible for a map to contain itself as a key.
```



The problem is that you are using as key not a standard object (any object with well defined ```equals``` and ```hashCode``` methods, that is not the map itself), but the map itself.

The problem is on how the ```hashCode``` of the ```HashMap``` is calculated:

```public int hashCode() {
   int h = 0;
   Iterator<Entry<K,V&gt;&gt; i = entrySet().iterator();
   while (i.hasNext())
       h += i.next().hashCode();
   return h;
}
```

As you can see, to calculate the hashCode of the map, it iterates over all the elements of the map. And for each element, it calculates the hashCode. Because the only element of the map has as key is the map itself, it becomes a source of recursion. 

Replacing the map with another object that can be used as key (with well defined ```equals``` and ```hashCode```) will work:

```import java.util.HashMap;

 public class Test {
   public static void main(String[] args) {
     HashMap hm = new HashMap();

     String key = "k1";
     hm.put(key, "1");
     hm.put(key, "2");
   }
} 
```

Comment for this answer: This is imho now a good answer. Downvote converted to upvote.
Comment for this answer: Why isn't this a compile time error if it's explicitly prohibited in the docs.
Comment for this answer: What is a standard object?
Comment for this answer: Why not just have `public int hashCode() {throw new RuntimeException("Hashcode of a Hashmap is undefined!");}`? Sure in this way you prevent the `HashMap` to be used as a key for a *different* mapping, but that's probably a bad idea anyway...
Comment for this answer: Any object that can be used as key. So with well defined hashCode and equals methods
Comment for this answer: @SleimanJneidi I added also an explicit reference from the javadoc telling that is not possible to add a Map to itself as key.
Comment for this answer: @AshBurlaczenko there are too many ways to put a key on the map. Is not simple (and not correct to check all of them at compile time). Additionally is counter intuitive to add a data structure to itself.

Here is another answer: You are using same object name as a key so it is infinite loop.

so it is stack overflow. 


Here is another answer: Problem is not that hash map blows up the stack for "same key" entered twice, but because your particular choice of map key. You are adding hash map to itself. 

To explain better - part of Map contract is that keys must not change in a way that affects their equals (or hashCode for that matter) methods.

When you added map to itself as a key, you changed key (map) in a way that is making it return different hashCode than when you first added map.

For more information this is from JDK dock for Map interface:

```
  Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map. A special case of this prohibition is that it is not permissible for a map to contain itself as a key. While it is permissible for a map to contain itself as a value, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a map.
```


Here is another answer: In order to locate a key in the ```HashMap``` (which is done whenever you call ```put``` or ```get``` or ```containsKey```), ```hashCode``` method is called for the key. 

For ```HashMap```, ```hashCode()``` is a function of the ```hashCode()``` of all the entries of the ```Map```, and each entry's ```hashCode``` is a function of the key's and value's ```hashCode```s. Since your key is the same ```HashMap``` instance, computing the ```hashCode``` of that key causes an infinite recursion of ```hashCode``` method calls, leading to ```StackOverflowError```.

Using a ```HashMap``` as a key to a ```HashMap``` is a bad idea.

Comment for this answer: Using a HashMap as a key is generally a bad idea, and especially it is forbidden adding the map as key to itself (as defined in the Map javadoc, see my answer)

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 5, 'CommentCount': 8, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2016:00:07/04/16', 'FavoriteCount': 1.0, 'PostTypeId': 1, 'Tags': '<java><hash><hashmap><stack-overflow>', 'Title': 'Infinite loop when using a key multiple times in HashMap', 'ViewCount': 1491, 'id': 38182022, 'user_AboutMe': '<p><em>“With foxes we must play the fox.”</em> - <strong>Dr. Thomas Fuller</strong></p>\n', 'user_AccountId': 4761031.0, 'user_DisplayName': 'T-Bag', 'user_Reputation': 10764.0, 'user_Views': 1423.0, 'user_id': 3848411.0}}