Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>To "fix" the code, you need to use a generic <em>bound</em>:</p> <pre><code>public void interfaceIsTheArgument(List&lt;? extends Weapon&gt; w) { ... } ... interfaceIsTheArgument(new ArrayList&lt;? extends Weapon&gt; ()); interfaceIsTheArgument(new ArrayList&lt;Knife&gt;()); </code></pre> <p>The key reason is <code>List&lt;Gun&gt;</code> is <strong>not</strong> a subclass of <code>List&lt;Weapon&gt;</code>. The reason for this fact can be illustrated by this code:</p> <pre><code>List&lt;Gun&gt; guns = new ArrayList&lt;Gun&gt;(); // If List&lt;Weapon&gt; was a super type of List&lt;Gun&gt;, this next line would be allowed List&lt;Weapon&gt; weapons = guns; // Won't compile, but let's assume it did weapons.add(new Knife()); // Compiles, because Knife is a Weapon Gun gun = guns.get(0); // Oops! guns.get(0) is a Knife, not a Gun! </code></pre> <p>By using the bound <code>&lt;? extends Weapon&gt;</code>, we are saying we'll accept any generic type that is a <em>subclass</em> of <code>Weapon</code>. Using bounds can be very powerful. This kind of bound is an <em>upper</em> bound - we are specifying the top-level class as being <code>Weapon</code>.</p> <p>There's also a <em>lower</em> bound, that uses this syntax:</p> <pre><code>List&lt;? super Weapon&gt; // accept any type that is a Weapon or higher in the class hierarchy </code></pre> <p>So, when to use each one? Remember this word <code>PECS</code>: "Producer extends, consumer super". This means on the producer side of the code (where the objects are <em>created</em>) use <code>extends</code>, and on the consumer side of the code (where the objects are <em>used</em>) us <code>super</code>. Once you try it a few times, you'll understand through experience why it works well.</p> <p><a href="https://stackoverflow.com/questions/2723397/java-generics-what-is-pecs">This SO question/answer</a> covers it well.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload