Return to site

☕🎓JAVA CERTIFICATION QUESTION: Unmodifiable maps

April 30, 2023

Given the following map:

☕🎓JAVA CERTIFICATION QUESTION: Unmodifiable maps

Given the following map:

var m = Map.of(1,2,3,4);

Which code fragment is guaranteed to print 37 to the console? Choose one.

A. m.forEach((x, y) -> System.out.print(x + y));

 

B. for (var v : m) {

System.out.print(v.getKey() + v.getValue());

}

 

C. for (var v : m.keySet()) {

System.out.print(v + m.get(v));

}

 

D. for (var t : m.entrySet()) {

System.out.print(t.getKey() + t.getValue());

}

 

E. None of the above

#java #certificationquestion #ocp

Answer: None of the above

Look at the effect of the Map.of(1,2,3,4) method call.

It creates a Map〈Integer, Integer〉 with two key-value pairs.

The keys for these pairs are 1 and 3, and the corresponding values are 2 and 4.

Note that the Map.of methods that take arguments in this form treat those arguments as a key, a value, a key, a value, and so on.

The keys and values, of course, will be autoboxed to provide Integer objects.

Since you have two pairs in this Map—1-2 and 3-4—i

t’s a simple observation of arithmetic that adding the key-value pairs will give the results 3 and 7,

which seems at least promising for producing the desired output.

Now, look at the code of each option in turn.

m.forEach((x, y) -> System.out.print(x + y));

The map.forEach method in this case accepts a BiConsumer〈Integer, Integer〉 as its argument,

and the accept method of that argument will be called with a key and value pair from each key-value pair.

But the iteration of a Map in Java does not provide a predictable order.

for (var v : m) {

System.out.print(v.getKey() + v.getValue());

}

will not compile because java.util.Map itself does not implement the Iterable interface required for use in an enhanced for loop.

for (var v : m.keySet()) {

System.out.print(v + m.get(v));

}

extracts a keySet from the Map, which gives you a set of the keys.

But the iteration of a Map in Java does not provide a predictable order.

iterates over a Set of Map.Entry objects.

But the iteration of a Map in Java does not provide a predictable order.

So none of the answers are correct.

https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/util/Map.html#unmodifiable -> “The iteration order of mappings is unspecified and is subject to change.”