1Z0-819 · Question #155
Given: public class X { private Collection collection; public void set (Collection collection) { this.collection = collection; } } and public class Y extends X { public void set (Map<String,String>…
The correct answer is B. set(map.values()); D. super.set(map.values()). Options B and D work because Map.values() returns a Collection<String>, which is assignment-compatible with the raw Collection parameter in X.set(Collection). B calls the inherited set(Collection) via the normal dispatch chain (Y inherits it from X), and D does the same thing…
Question
Options
- Amap.forEach((k, v)->set(v));
- Bset(map.values());
- Csuper.<String,String>map
- Dsuper.set(map.values());
- Eset(map)
How the community answered
(56 responses)- A13% (7)
- B79% (44)
- C4% (2)
- E5% (3)
Explanation
Options B and D work because Map.values() returns a Collection<String>, which is assignment-compatible with the raw Collection parameter in X.set(Collection). B calls the inherited set(Collection) via the normal dispatch chain (Y inherits it from X), and D does the same thing with an explicit super. call - both pass a valid Collection to X's setter.
Why the others fail:
- A (
map.forEach((k, v)->set(v))) -vis aString, soset(v)looks for aset(String)method that doesn't exist in X or Y; won't compile. - C (
super.<String,String>map) - Invalid syntax entirely;mapis a local parameter, not a method, so this doesn't parse as a valid statement. - E (
set(map)) - Inside Y'sset(Map<String,String>), callingset(map)resolves back to Y's own method (Map matches Y's signature before X's Collection), causing infinite recursion. Even if it compiled, it never reaches X's setter.
Memory tip: In Java, Map is not a Collection - they are parallel interfaces under java.util. Whenever you need to bridge a Map to a Collection, reach for map.values() (Collection), map.keySet() (Set), or map.entrySet() (Set) - all three are legitimate Collections.
Topics
Community Discussion
No community discussion yet for this question.