Which code, when inserted independently at (1), will result in the following output from the program: {1=Odd, 2=Even, 3=Odd}?
import java.util.Map; import java.util.TreeMap; public class Main { public static void main(String[] args) { Map<Integer, String> myMap = new TreeMap<Integer, String>(); for (Integer key : new int[] {1, 2, 1, 3, 1, 2, 3, 3}) { // (1) INSERT CODE HERE ... }//from www .j ava 2s .c om System.out.println(myMap); } private static String toggle(String str) { if (str.equals("Odd")) str = str.replace("Odd", "Even"); else str = str.replace("Even", "Odd"); return str; } }
Select the one correct answer.
(a) String value = myMap.get(key); myMap.put(key, (value == null) ? "Odd" : Main.toggle(value)); (b) String value = myMap.get(key); if (value == null) value = "Odd"; else//from w w w . j av a 2 s .c o m Main.toggle(value); myMap.put(key, value); (c) String value = myMap.get(key); if (!myMap.containsKey(key)) myMap.put(key, "Odd"); else Main.toggle(value); (d) All of the above.
(a)
Strings are immutable.
In (b) and (c) the argument value in the call to the method toggle()
refers to the old string after completion of the call, so the value in the map is not updated with the new string.