HashMap ConcurrentModificationException


What is wrong with my code here?

  private HashMap mappings;

  private void prune() {
    // for every mapping in mappings
    Iterator it = mappings.keySet().iterator();
    while (it.hasNext()) { // for every mapping
      String key = (String) it.next();
      Object o = mappings.get(key);
      if (!(o instanceof ArrayList)) // if not an ArrayList
        mappings.remove(key); // delete mapping

      at java.util.HashMap$HashIterator.nextEntry(HashMap.java:762)
      at java.util.HashMap$KeyIterator.next(HashMap.java:798)
      at com.test.MappingsGrid.prune(MappingsGrid.java:73)
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

how do u run this code?
anyway try:
      if (!(o instanceof ArrayList)) // if not an ArrayList
        mappings.remove(key); // delete mapping
>        mappings.remove(key); // delete mapping

that should be:


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
you cannot delete entries directly from the map while you are iterating thru it
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

If more than one thread is involved, create your Map thus:

Map synchMappings = Collections.synchronizedMap(mappings);

and then operate on 'synchMappings'
ycompAuthor Commented:
sorry.. forgot to say it is a single thread.

objects: that's what I was thinking... any ideas how I should do what I want to do.. i.e. delete those mappings w/o throwing an exception?
ycompAuthor Commented:
objects: sorry I should read more carefully next time.. I'll check out it.remove()
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.