Which code, when inserted independently at (1), will result in the following output from the program: {Soap=10, Salts=10}?
import java.util.*; public class Main { public static void main(String[] args) { NavigableMap<String, Integer> myMap = new TreeMap<String, Integer>(Collections.reverseOrder()); myMap.put("Soap", 10); myMap.put("Shampoo", 5); myMap.put("Salts", 10); // (1) INSERT CODE HERE ... System.out.println(myMap);/*w w w . j av a 2 s.c o m*/ } }
Select the two correct answers.
(a) for (Map.Entry<String, Integer> entry : myMap.entrySet()) if (entry.getKey().equals("Shampoo")) myMap.remove("Shampoo"); (b) for (Iterator<String> iterator = myMap.keySet().iterator(); iterator.hasNext();)//ww w . j a va 2 s . co m if (iterator.next().equals("Shampoo")) iterator.remove(); (c) for (Iterator<String> iterator = myMap.keySet().iterator(); iterator.hasNext();) { if (iterator.next().equals("Shampoo")) myMap.remove("Shampoo"); (d) for (Map.Entry<String, Integer> entry : myMap.entrySet()) if (entry.getKey().equals("Shampoo")) myMap.remove(entry); (e) myMap.subMap("Shampoo", true, "Shampoo", true).clear();
(b) and (e)
(a) throws a ConcurrentModificationException.
We cannot remove an entry in a for(:) loop.
(c) throws a ConcurrentModificationException as well, even though we use an iterator.
The remove()
method is called on the map, not on the iterator.
The argument to the remove()
method of the map must implement Comparable, Map.
Entry does not, resulting in a ClassCastException in (d).
We can remove an entry from the underlying map when traversing the key set using an iterator, as in (b).
(e) creates a map view of one entry and clears it, thereby also clearing it from the underlying map.