I saw java hash map ,the clear method,like this:
public void clear() {
modCount++;
Entry[] tab = table;
for (int i = 0; i < tab.length; i++)
tab[i] = null;
size = 0;
}
I don't understand,why to take new tab to clear.
Why not use table to clear?
I don't understand, why new tab to clear.
It is not a new table ... it is just a local variable.
I can think of three possible reasons:
Readability, as suggested by @Bhesh Gurung ... though it hardly makes a difference here (IMO).
It might mitigate (somewhat) the damage caused if one thread calls clear()
while a second thread does an update that might cause the table to be expanded. But it certainly doesn't fix the problem, so I'd be inclined to dismiss this as being nonsensical.
It might improve performance; e.g. since the optimizer knows that the reference in the local variable tab
cannot change, it can optimize the array bounds checks better.
Of these, I think that the 3rd reason is the most plausible.
(I don't think it is anything to do with the transient
modifier. In this case, the modifier is only there for readability. The HashMap
class provides readObject
and writeObject
which renders the transient
modifier moot.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With