Could not understand implementation of clear HashMap method in java

I saw a java hash map, a clear method, for example:

public void clear() { modCount++; Entry[] tab = table; for (int i = 0; i < tab.length; i++) tab[i] = null; size = 0; } 

I do not understand why you need to remove the new tab.

Why not use a table for cleaning?

+6
source share
2 answers

I don’t understand why a new tab is needed.

This is not a new table ... this is just a local variable.

I can think of three possible reasons:

  • The readability suggested by @Bhesh Gurung ... although it hardly matters (IMO) here.

  • It can reduce (somewhat) the damage caused by the fact that one thread calls clear() , and the second thread performs an update, which can lead to table expansion. But this certainly does not fix the problem, so I would be inclined to dismiss it as meaningless.

  • This can improve performance; for example, since the optimizer knows that the link in the local variable tab cannot change, it can better optimize checks on the bounds of the array.

Of these, I think the 3rd reason is the most plausible.

(I don't think this has anything to do with the transient modifier. In this case, the modifier is read-only. The HashMap class provides readObject and writeObject , which transient displays.)

+4
source

This may be because the table field is declared transient , so it is not part of the constant state of the HashMap object. The table field is replaced in methods such as resize() , which is not synchronized, so it is possible that the table field was replaced below you when repeating all its entries inside the clear() method call. If it first refers to table and iterates over that link, we guarantee that if the table field changes, we will iterate through the original table anyway.

+2
source

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


All Articles