Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could not understand implementation of clear method of HashMap in java

Tags:

java

hashmap

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?

like image 746
user1626860 Avatar asked Aug 27 '12 05:08

user1626860


1 Answers

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.)

like image 62
Stephen C Avatar answered Sep 20 '22 14:09

Stephen C