Note that there are some explanatory texts on larger screens.

plurals
  1. POProblem with unbounded Java Generic interface
    primarykey
    data
    text
    <p>Consider the following simple code</p> <pre><code>import java.util.*; public class MainTest&lt;T extends Object1&lt;?,?&gt;&gt; { List&lt;T&gt; list; public MainTest(List&lt;T&gt; l) { this.list=l; } public int testCompare() { // fails to compile here return list.get(0).compareTo(list.get(1)); } public static void main(String[]args) { List&lt;Object1Impl&gt; list = new ArrayList&lt;Object1Impl&gt;(); list.add(new Object1Impl()); list.add(new Object1Impl()); MainTest&lt;Object1Impl&gt; test = new MainTest&lt;Object1Impl&gt;(list); System.out.println(test.testCompare()); } } interface Object1&lt;E, V&gt; extends Comparable&lt;Object1&lt;E,V&gt;&gt; { } class Object1Impl implements Object1&lt;Integer, Integer&gt;{ public int compareTo(Object1&lt;Integer, Integer&gt; o) { return 0; } } </code></pre> <p>I am aware that in this case the program will not compile (fails at testCompare() because T is extending unbounded <code>Object1&lt;?,?&gt;</code>). Is there any alternative to fix this besides making <code>MainTest&lt;T extends Object1&lt;E,V&gt;,E,V&gt;</code>?</p> <p>EDIT: the error message is</p> <pre><code>The method compareTo(Object1&lt;capture#1-of ?,capture#2-of ?&gt;) in the type Comparable&lt;Object1&lt;capture#1-of ?,capture#2-of ?&gt;&gt; is not applicable for the arguments (T) </code></pre> <p>I have read Effective Java book but still can't really think of a solution..</p> <p>Also, why is it that if I change interface Object1 into an abstract class the program will compile without any problem? This really puzzles me...</p> <p>EDIT: when I mean changing into abstract class is as follows</p> <pre><code>abstract class Object1&lt;E, V&gt; implements Comparable&lt;Object1&lt;E,V&gt;&gt;{ public int compareTo(Object1&lt;E,V&gt; o) { return 0; } } class Object1Impl extends Object1&lt;Integer, Integer&gt;{ } </code></pre> <p>this will work (only if using Eclipse, compiling it manually using javac does not work) but I have no idea why</p>
    singulars
    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