title: Uses for the strange-looking explicit type argument declaration syntax in Java
body: <p>I recently came upon the strange syntax for explicitly declaring generic types when calling Java methods. For example:</p>
  
  <pre><code>Collections.&lt;String&gt;emptyList();
  </code></pre>
  
  <p>returns an empty <code>List&lt;String&gt;</code>. However, this seems silly as the implementation of <code>&lt;T&gt; emptyList()</code> is just the unchecked type cast <code>(List&lt;T&gt;) EMPTY_LIST</code>, such that all results have the same type erasure (and are the same object.) Moreover, this sort of explicit type declaration is usually not needed because the compiler can often infer the types:</p>
  
  <pre><code>List&lt;String&gt; empty = Collections.emptyList();
  </code></pre>
  
  <p>After doing some more digging I found two other times where you'd want to use this syntax, and they're all due to using the Guava library and <strong>apparently trying to put too many statements on one line</strong>.</p>
  
  <ol>
  <li><p>Decorating a collection, for example with a synchronized wrapper, and the compiler being not able to infer the types. The following doesn't work if you take out the type declaration: <code>cannot convert from Set&lt;Object&gt; to Set&lt;String&gt;</code>:</p>
  
  <pre><code>Set&lt;String&gt; set = Collections.synchronizedSet(Sets.&lt;String&gt;newHashSet());
  </code></pre></li>
  <li><p>Getting less specific type parameters when they compiler tries to make ones that are too specific. For example, without the type declaration the following statement complains as well: <code>cannot convert from Map&lt;String, String&gt; to Map&lt;String, Object&gt;</code>:</p>
  
  <pre><code>Map&lt;String, Object&gt; toJson = ImmutableMap.&lt;String, Object&gt;of("foo", "bar");
  </code></pre></li>
  </ol>
  
  <p>I find it ironic that in the first case the inferred type parameters are too general and in the second case they are too specific, but I suppose that is just an artifact of the generics system in Java. </p>
  
  <p>However, this language construct itself seems to be avoidable except in these <a href="http://code.google.com/p/guava-libraries/issues/detail?id=883" rel="nofollow">strange use cases invented by the Guava team</a>. Moreover, it seems plain to me that <strong>there <em>is</em> a way for the compiler to infer type arguments in both the above examples</strong>, and the developers just chose not to do so. Are there examples of it ever being necessary or useful to use this construct in Java programming or does it exist solely to make the compiler simpler / JDK developer's life easier?</p>