简体   繁体   中英

In java.util.HashMap, why modcount is not a boolean?

In java.util.HashMap, the member variable modCount seems to be getting used mainly to detect concurrentmodification. Then what is the need of keeping that variable an int, cant this be achieved with a bool?

Having a modification count, rather than a boolean, lets multiple iterators keep track of whether they are valid or not simultaneously.

If modifications were tracked with a boolean, than all iterators would need to be in the same state of validity. A count lets an iterator know how many modifications happened when it was created. So if the number of modifications when it is used is different, than it knows it's invalid. That allows for some iterators to be valid and some to be invalid, all without ever needing to manually update the validity of each iterator.

If you had a boolean there, it would mean that before calling the iterator you'd have to set it to false , and when you finish, you'd check if it's true , right?

But if you did that, and you created two iterators, or created an iterator and called the forEach method, then the second iterator would reset the variable again.

Iterator<K> keyIterator = map.keySet().iterator();
...
keyIterator.next();
...
map.put(key,value);

Iterator<Map.Entry<K,V>> pairIterator = map.entrySet().iterator();
...
keyIterator.next();

Now, this last call to keyIterator.next() should fail, because of the map.put(key,value) call in the middle. But if we work by resetting a boolean, then map.EntrySet().iterator() must have cleared the boolean flag. And thus, keyIterator.next() will not fail.

Using an integer avoids this problem, because none of the iterators actually changes the state of the map - only the modifying operations do. The variable that keeps the "old value" is kept locally, and thus does not interfere with other readers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM