Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are certain places, where wildcards, and type parameters do the same thing. But there are also certain places, where you have to use type parameters. </p> <ol> <li>If you want to enforce some relationship on the different types of method arguments, you can't do that with wildcards, you have to use type parameters. </li> </ol> <p>Taking your method as example, suppose you want to ensure that the <code>src</code> and <code>dest</code> list passed to <code>copy()</code> method should be of same parameterized type, you can do it with type parameters like so:</p> <pre><code>public static &lt;T extends Number&gt; void copy(List&lt;T&gt; dest, List&lt;T&gt; src) </code></pre> <p>Here, you are ensured that both <code>dest</code> and <code>src</code> have same parameterized type for <code>List</code>. So, it's safe to copy elements from <code>src</code> to <code>dest</code>.</p> <p>But, if you go on to change the method to use wildcard:</p> <pre><code>public static void copy(List&lt;? extends Number&gt; dest, List&lt;? extends Number&gt; src) </code></pre> <p>it won't work as expected. In 2nd case, you can pass <code>List&lt;Integer&gt;</code> and <code>List&lt;Float&gt;</code> as <code>dest</code> and <code>src</code>. So, moving elements from <code>src</code> to <code>dest</code> wouldn't be type safe anymore. If you don't need such kind of relation, then you are free not to use type parameters at all.</p> <p>Some other difference between using wildcards and type parameters are:</p> <ul> <li>If you have only one parameterized type argument, then you can use wildcard, although type parameter will also work.</li> <li>Type parameters support multiple bounds, wildcards don't.</li> <li><p>Wildcards support both upper and lower bounds, type parameters just support upper bounds. So, if you want to define a method that takes a <code>List</code> of type <code>Integer</code> or it's super class, you can do:</p> <pre><code>public void print(List&lt;? super Integer&gt; list) // OK </code></pre> <p>but you can't use type parameter:</p> <pre><code> public &lt;T super Integer&gt; void print(List&lt;T&gt; list) // Won't compile </code></pre></li> </ul> <hr /> <p><strong>References:</strong></p> <ul> <li><a href="http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeArguments.html#FAQ203" rel="noreferrer">Angelika Langer's Java Generics FAQs</a></li> </ul>
 

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