title: Use generic to store common supertype in Java
body: <p>Suppose I have a method "mix" that takes two Lists of possibly different types T and S and returns a single List containing the elements of both. For type-safety, I'd like to specify that the returned List is of a type R, where R is a supertype common to both T and S. For example:</p>
  
  <pre><code>List&lt;Number&gt; foo = mix(
      Arrays.asList&lt;Integer&gt;(1, 2, 3),
      Arrays.asList&lt;Double&gt;(1.0, 2.0, 3.0)
  );
  </code></pre>
  
  <p>To specify this, I could declare the method as</p>
  
  <pre><code>static &lt;R, T extends R, S extends R&gt; List&lt;R&gt; mix(List&lt;T&gt; ts, List&lt;S&gt; ss)
  </code></pre>
  
  <p>But what if I want to make <code>mix</code> an instance method instead of static, on the class <code>List2&lt;T&gt;</code>?</p>
  
  <pre><code>&lt;R, T extends R, S extends R&gt; List&lt;R&gt; mix ...
  </code></pre>
  
  <p>shadows the <code>&lt;T&gt;</code> on the instance of <code>List2</code>, so that's no good.</p>
  
  <pre><code>&lt;R, T extends S&amp;T, S extends R&gt; List&lt;R&gt; mix ...
  </code></pre>
  
  <p>solves the shadowing problem, but isn't accepted by the compiler</p>
  
  <pre><code>&lt;R super T, S extends R&gt; List&lt;R&gt; mix ...
  </code></pre>
  
  <p>is rejected by the compiler because lower-bounded wildcards can't be stored in a named variable (only used in <code>? super X</code> expressions)</p>
  
  <p>I could move the arguments to the class itself, like <code>List2&lt;R, T extends R, S extends R&gt;</code>, but the type information really has no business being on the instance level, because it's only used for one method call, and you would have to re-cast the object every time you wanted to invoke the method on different arguments.</p>
  
  <p>As far as I can tell, there's no way to do this with generics. The best I can do would be to return a raw <code>List2</code> and cast it at the callsite, like before generics were introduced. Does anybody have a better solution?</p>