Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can we add an element in hashtable while iterating

 
Ruchika Kapoor
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 15436
41
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic