File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Can we add an element in hashtable while iterating Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Can we add an element in hashtable while iterating" Watch "Can we add an element in hashtable while iterating" New topic

Can we add an element in hashtable while iterating

Ruchika Kapoor

Joined: Oct 03, 2004
Posts: 22
Hello Friends,

I've a query related to HashMap.

Can we add/modify an element while iterating through a HashMap. As per my knowledge, we can either get an enumerator or iterator on a HashMap. An iterator provides only remove() method, while an Enumerator returns elements in read-only mode.

Is there any way out if we need to change or add a new element into it while iterating or can we get a listiterator on a HashMap.

Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15092

No, you can't; if you try this, you will get a ConcurrentModificationException when you use the iterator after modifying the map. The API documentation of class HashMap tells you:
The iterators returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException.

You cannot get a ListIterator for a HashMap, because ListIterator is for lists, and a map is not a list.

Find a different strategy for solving the problem; for example, first collect all the elements that you want to add to the map in a different map, and then when you're done iterating, use putAll() on the original HashMap to put the new elements in the map.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
I agree. Here's the link:
subject: Can we add an element in hashtable while iterating
It's not a secret anymore!