When I'm new to Hashtable, why is the put method called?

I am reading the Hashtable code and am confused and have some questions. I am encoded as follows:

 Hashtable table = new Hashtable(); table.put(table, 1); int code = table.hashCode(); 

I have two questions:

  • When I call the hashCode method, like the third line code, why is it not an infinite loop? I think this is an endless loop.

  • When I debug this code, I found that the new Hashtable() code would call the put method, why?

+4
source share
2 answers
  • According to the OpenJDK source I'm reading , there is a defender written specifically to protect against the case where the Hashtable contains itself.

  • I do not see put references inside the constructor. Do you have a footprint that you could post in your answer?

+7
source

First, in many cases, use a hash map.

Secondly, it uses an Oracle implementation .

This is not an endless cycle. HashTable.hashCode( just repeats through map elements once. Not infinitely. If the table does not contain itself, where to the source , I found that it is really very hacked, but prevents recursion. In this case, it skips calculating its own hash code that returns 0.

  • Looking at the source, put( called. Only the next line calls Put .
0
source

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


All Articles