I am iterating over, and modifying a map (which is created from an existing group of enum objects) like the following:
public class Dispenser {
private Map<Ingredient, Integer> availableIngredients =
new EnumMap<Ingredient, Integer>(Ingredient.class);
public void orderSandwich(SandwichType sandwichType) {
Map<Ingredient, Integer> buffer =
new EnumMap<Ingredient, Integer>(availableIngredients);
for (Map.Entry<Ingredient, Integer> entry :
sandwichType.getIngredients().entrySet()) {
Integer currentUnits = buffer.get(entry.getKey());
buffer.put(entry.getKey(), currentUnits - entry.getValue());
}
availableIngredients.clear();
availableIngredients.putAll(buffer);
}
}
I wanted to ask if the temporary, method-local, buffer collection is necessary in this case. I mean, it works fine as it is but not sure its benefits. I have to clear my original collection and replace it with the contents of the buffer collection, which is basically the actual map that is modified within the loop.
Since, it works fine without the buffer collection (using only my original collection), I was wondering if one approach is recommended over the oter and why.
Many thanks for any advice on best practices on this.