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, StringBuilder> myMap = new TreeMap<Integer, StringBuilder>(); for (Integer key : new int[] {1, 2, 1, 3, 1, 2, 3, 3}) { // (1) INSERT CODE HERE ... }//from w ww. j a v a 2 s .c o m System.out.println(myMap); } private static StringBuilder toggle(StringBuilder strBuilder) { String value = "Odd"; if (strBuilder.toString().equals(value)) value = "Even"; return strBuilder.replace(0, strBuilder.length(), value); } }
Select the one correct answer.
(a) StringBuilder value = myMap.get(key); myMap.put(key, (value == null) ? new StringBuilder("Odd") : Main.toggle(value)); (b) StringBuilder value = myMap.get(key); if (value == null) value = new StringBuilder("Odd"); else/*from w w w .j av a2s. c o m*/ Main.toggle(value); myMap.put(key, value); (c) StringBuilder value = myMap.get(key); if (!myMap.containsKey(key)) myMap.put(key, new StringBuilder("Odd")); else Main.toggle(value); (d) All of the above.
(d)
StringBuilders are mutable.
A string builder's state can be modified by any of its aliases, in this case by the reference value.