This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
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
Author

Can we add an element in hashtable while iterating

Ruchika Kapoor
Greenhorn

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.


Thanks,
Ruchika
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

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 7 API documentation
Scala Notes - My blog about Scala
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Can we add an element in hashtable while iterating
 
Similar Threads
Iterator are fail safe while Enumeration is not
HashMap vs Hashtable
add element to list while iterating it.
How To Get Rid Of java.util.ConcurrentModificationException?
Do I have to use an iterator?