1

I wrote the following code:

final Iterator<Entry<Label, Label>> it = dataLabels.entrySet().iterator();
while (it.hasNext()) {
    final Map.Entry<Label, Label> pairs = it.next();
    dataLabels.remove(pairs.getKey());
    pairs.getValue().dispose();
    pairs.getKey().dispose();
}

It iterates over a map of labels (type: Map<Label, Label>) and dispose of each one of them (after removing it from the map).

I feel like this code does not do what I expect. I think that it stops iterating after the first loop (tried to add printed message to see the behavior).

Does the code do what I expect (disposing of all the labels)? If not, how to fix it?

vesii
  • 2,760
  • 4
  • 25
  • 71
  • 1
    Did you try running your code? It should throw a ConcurrentModificationException, since you can`t change the map while you are iterating over it. – second Jun 30 '19 at 02:19
  • 1
    Use the iterator to remove it from the map, see https://stackoverflow.com/questions/1196586/calling-remove-in-foreach-loop-in-java – second Jun 30 '19 at 02:20

2 Answers2

0

You can't call remove on a map while you are iterating through the entries.

You can either use the iterator remove method as shown in the other answer or just clear the map at the end:

for (Map.Entry<Label, Label> dataLabel : dataLabels.entrySet()) {
  dataLabel.getKey().dispose();
  dataLabel.getValue().dispose();
}
dataLabels.clear();

or using streams:

dataLabels.forEach((key, value) -> { key.dispose(); value.dispose(); });
dataLabels.clear();
greg-449
  • 109,219
  • 232
  • 102
  • 145
-1

If you want to remove one by one try this,

    Iterator<Map.Entry<Label,Label>> i = dataLabels.entrySet().iterator();
    while (i.hasNext()) {
       Map.Entry<String,String> entry = i.next();
       // Do something
       i.remove();
    }

or else you can clear entire map using dataLabels.clear()

By using dataLabels.clear() you can reuse the dataLabels map.

If you don't need to reuse it set it to null

dataLabels = null;
Tenusha Guruge
  • 2,147
  • 3
  • 18
  • 38
  • We`ll he could just use clear() on the map, after he is done disposing in that case. No need for a second iteration. – second Jun 30 '19 at 02:26