nerdexam
Oracle

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…

Working with Arrays and Collections

Question

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> map) { super.set(map); // line 1 } } Which two lines can replace line 1 so that the Y class compiles? (Choose two.)

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)
  • A
    13% (7)
  • B
    79% (44)
  • C
    4% (2)
  • E
    5% (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))) - v is a String, so set(v) looks for a set(String) method that doesn't exist in X or Y; won't compile.
  • C (super.<String,String>map) - Invalid syntax entirely; map is a local parameter, not a method, so this doesn't parse as a valid statement.
  • E (set(map)) - Inside Y's set(Map<String,String>), calling set(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

#inheritance#collections hierarchy#method overloading#type compatibility

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice