Note that there are some explanatory texts on larger screens.

plurals
  1. PONested Type Parameters in Java
    primarykey
    data
    text
    <p>This is an example which I made up to be a simplification of my real code, so I apologize if it is a little contrived. What I would like to do is to effectively get two type parameters out of a single nested type argument. I'm pretty sure this is impossible, but I thought I'd give it a shot.</p> <pre><code>//Not legal java code public class Foo&lt;C extends Collection&lt;T&gt;&gt; { //where T is another type parameter private C coll; public Foo(C coll) { this.coll = coll; } public void add(T elem){ this.coll.add(elem); } //UPDATED TO ADD GETTER /** * I may need to retrieve the collection again, or pass it * on to another function that needs the specific C type */ public C getColl(){ return coll; } } ... List&lt;String&gt; strings = new ArrayList&lt;String&gt;(); Foo&lt;List&lt;String&gt;&gt; foo = new Foo&lt;List&lt;String&gt;&gt;(strings); foo.add("hello"); </code></pre> <p>I know that I could do it by adding another type parameter:</p> <pre><code>public class Foo&lt;C extends Collection&lt;T&gt;,T&gt; </code></pre> <p>but then I have to add the redundant:</p> <pre><code>Foo&lt;List&lt;String&gt;,String&gt; foo = new Foo&lt;List&lt;String&gt;,String&gt;(strings); </code></pre> <p>And in my real world case, my generics can sometimes be specified in the implements clause like</p> <pre><code>public class Bar implements Baz&lt;String&gt; </code></pre> <p>Having to specify that second type parameter is even more painful then, because it feels like it throws the implementation details in my face. Having to say</p> <pre><code>Foo&lt;Bar,String&gt; </code></pre> <p>when there is a relationship between String and Bar already, just seems inelegant. I get that its Java, so that goes with the territory, but just curious if there was a solution for this.</p>
    singulars
    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