Note that there are some explanatory texts on larger screens.

plurals
  1. POJava Generics: How does method inference work when wildcard is being used in the method parameters?
    text
    copied!<p>Supposedy i have the following: </p> <pre><code>class x { public static void main(String [] args) { List &lt;?&gt; a = new LinkedList&lt;Object&gt;(); List &lt;? extends Object&gt; b = new LinkedList&lt;Object&gt;(); List &lt;? super Object&gt; c = new LinkedList&lt;Object&gt;(); abc(a, "Hello"); // (1) Error abc(b, "Hello"); // (2) Error abc(c, "Hello"); // (3) ok def(b); // (4) ok // Showing inference at work Integer[] a = {10, 20, 30}; // (5) T is inferred to be ? extends Object Method signature: ppp(? extends Object, ? extends Object[]) Method call signature: ppp(String, Integer[]); ppp("Hello", a); // ok } static &lt;T&gt; void abc(List&lt;T&gt; a, T b) {} static &lt;T&gt; void def(List&lt;T&gt; a) {} static &lt;T&gt; void ppp(T t1, T[] t2){} } </code></pre> <p>To begin with, look at clause 5 showing inference at work. Now clause 5 section is a working section.</p> <p>If that is what it is, then why does clause (1) &amp; (2) have errors? </p> <p>From my view, all these 3 methods calling have the same inference generated since no actual type parameters is used on the abc method call.</p> <p>method parameter &#060;T> abc (List &#060;T> a, T b>)<br> inferred &#060;Object> abc (List &#060;Object>, Object) // (4) </p> <p>Please bear in mind, method abc() and def() is my method. Compiler doesn't know what i want to do with the List in this method. I might just print the list size or might not even do anything at all as shown above. So there is no get or set involved here.</p> <p>CONTINUATION --> This is getting very confusing for me.</p> <pre><code>class y { public static void main(String [] args) { List &lt;Integer&gt; a = new LinkedList&lt;Integer&gt;(); List &lt;Object&gt; b = new LinkedList&lt;Object&gt;(); ppp("Hello", new Integer(1)); // (20) ok qqq("Hello", a); // (21) error qqq("Hello", b); // (22) ok } static &lt;T&gt; void ppp(T t1, T t2) {} static &lt;T&gt; void qqq(T t1, List &lt;T&gt; t2) {} } </code></pre> <p>Note that clause 21 is the same as clause 20 except 2nd parameter is being made to be a List instead of Integer.</p> <p>Clause 20 is ok cos' T is inferred to be Object.<br> Clause 22 is ok. Same reason as clause 20.<br> Clause 21 failed? T could also be inferred to be Object too - would work too?</p>
 

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