Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think that the simple answer is that you cannot do that. If the type of one of a classes attributes depends on a type parameter, that parameter has to be declared at the class level. And I don't think that it "makes sense" any other way.</p> <p>If <code>T</code> in your example is not a type parameter of the class, what is it? It cannot be the type parameter of the method, because that type is determined by how the method is called. (If the method is called in different static contexts with different inferred types for <code>T</code>, what is the notional type of <code>T</code> in the context of the attribute declaration?)</p> <p>So to bring this back to what you are trying to do here, an instance of <code>MyClass</code> will hold elements of some type, and you want to be able to insert and remove elements in a statically typesafe fashion. But at the same time you don't want to be able to say what that type is. So how is the compiler supposed to <strong>statically</strong> distinguish between a <code>MyClass</code> instance that holds (say) <code>Integer</code> objects and one that holds <code>String</code> objects?</p> <p>I don't even think you could implement this with explicit dynamic typechecks. (I think that type erasure means that the implementation of the <code>getSortedList()</code> method cannot find out what actual type is bound to its return type.)</p> <p>No. The real solution is to make <code>MyClass</code> a generic class that declares the type parameter <code>T</code>; e.g.</p> <pre><code>public class MyClass &lt;T extends Comparable&lt;T&gt;&gt; { </code></pre> <p>and remove the declaration of the method-level type parameter <code>T</code> from the two methods.</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