Link to home
Start Free TrialLog in
Avatar of DJ_AM_Juicebox
DJ_AM_Juicebox

asked on

Ok to delete element from HashMap while iterating?

Hi,

Is it legal to remove an element from a HashMap while iterating over it? Something like:

  HashMap<Integer, String> test = new HashMap<Integer, String();
  test.put(0, "a");
  test.put(1, "b");
  test.put(2, "c");

  for(Entry<Integer, String> entry : test.entrySet()){
      if (entry.getValue().equals("b")) {
          test.remove(entry.getKey());
      }
      // Ok to keep iterating?
  }

Thanks
Avatar of Mick Barry
Mick Barry
Flag of Australia image

you can but you need to use an Iterator and its remove() method'
How you are doing it will not work
Avatar of DJ_AM_Juicebox
DJ_AM_Juicebox

ASKER

Ok but what do you mean with an iterator and a remove method?

Thanks
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial