Note that there are some explanatory texts on larger screens.

plurals
  1. POIssue with generic types of ArrayList and interface inheritance
    primarykey
    data
    text
    <p>I'm having trouble understanding why the following doesn't work and I'm sure the answer is related to something basic I am not understanding and hope someone can help.</p> <p>I understand about using interfaces in an <code>ArrayList</code> such that if I have:</p> <pre><code>public interface Weapon { ... } public class Gun implements Weapon { ...} public class Knife implements Weapon { ... } </code></pre> <p>you can then insert anything that implements Weapon into the an array of weapons:</p> <pre><code>ArrayList&lt;Weapon&gt; weapons = new ArrayList&lt;Weapon&gt;(); weapons.add(new Gun()); weapons.add(new Knife(); </code></pre> <p>I get that, but what is confusing me is the understanding of why <code>ArrayList&lt;Gun&gt;</code> isn't compatible with <code>ArrayList&lt;Weapon&gt;</code> in other ways. To illustrate, the following is legal:</p> <pre><code>public void interfaceIsTheArgument(Weapon w) { ... } ... interfaceIsTheArgument(new Gun()); interfaceIsTheArgument(new Knife()); </code></pre> <p>but the following is not:</p> <pre><code>public void interfaceIsTheArgument(ArrayList&lt;Weapon&gt; w) { ... } ... interfaceIsTheArgument(new ArrayList&lt;Gun&gt;()); interfaceIsTheArgument(new ArrayList&lt;Knife&gt;()); </code></pre> <p>because the last function call reports that the method isn't applicable for its arguments. </p> <p>My question is why if the method knows it tasks an <code>ArrayList</code> with an interface as the generic type, why isn't it okay to pass in an array list of knives in that last statement?</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.
 

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