Note that there are some explanatory texts on larger screens.

plurals
  1. POJava generics infers Object for nested method call instead of T if nested method argument is not typesafe
    primarykey
    data
    text
    <p>today I have ran into strange <code>javac</code> behavior regarding generic type inference. Here's example class to ilustrate this strange behavior:</p> <pre><code>import java.util.Map; import java.util.Collections; import java.util.HashMap; public class Test { protected &lt;T&gt; T strange(T t, Map&lt;String, String&gt; map) { return t; } protected void ok(Map&lt;String, String&gt; map) {} protected &lt;T&gt; T test(T t) { T res = strange(t , new HashMap&lt;String, String&gt;()); //Doesn't work //res = strange(t, new &lt;String, String&gt;HashMap()); ok(new &lt;String, String&gt;HashMap()); res = strange(t, Collections.&lt;String, String&gt;emptyMap()); //Doesn't work //res = strange(t, Collections.EMPTY_MAP); res = strange(t, (Map&lt;String, String&gt;) Collections.EMPTY_MAP); ok(Collections.EMPTY_MAP); return res; } } </code></pre> <p>Notice <code>//Doesn't work</code> comments. If you uncomment this code you will get strange compiler error:</p> <pre><code>Test.java:18: error: incompatible types res = strange(t, Collections.EMPTY_MAP); ^ required: T found: Object where T is a type-variable: T extends Object declared in method &lt;T&gt;test(T) </code></pre> <p>Strange thing is that error complains about <code>strange</code> method return type is Object and not T, but when second unsafe parameter is cast to correct type then T is inferred correctly. </p> <p>Can someone explain if this is correct behavior? Because it looks strange to me. Can it be a compiler bug? </p> <p>Why this line works</p> <pre><code>T res = strange(t , new HashMap&lt;String, String&gt;()); </code></pre> <p>and this one is doesn't?</p> <pre><code>T res = strange(t, new &lt;String, String&gt;HashMap()); </code></pre> <p>I have tested it with java 7 and 6.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    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.
 

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