当用Java做一些不太理想的事情时,我遇到了一个泛型错误,我无法理解为什么它不起作用。代码是:

package test;
import java.util.*;
public class TestClass {
  public static class A extends C{}
  public static class B extends C{}
  public static class C{}
  public static class D<T>{}
  public static class E<T>{}

  public static void main(String args[]){
      E<D<? extends C>> a = new E<D<A>>();
      E<D<? extends Object>> b = new E<D<? extends C>>();
      E<D<? extends A>> c = new E<D<A>>();
      E<D<? super A>> d = new E<D<A>>();
      D<? extends C> e = new D<A>();
      D<? extends A> f = new D<A>();
      D<? extends A> g = new D<A>();
  }
}

编译时出现的错误是:

test / TestClass.java:11:不兼容的类型
找到:test.TestClass.E >
必需:test.TestClass.E >
E > a =新的E >();
^
test / TestClass.java:12:不兼容的类型
找到:test.TestClass.E >
必需:test.TestClass.E >
E > b = new E >();
^
test / TestClass.java:13:不兼容的类型
找到:test.TestClass.E >
必需:test.TestClass.E >
E > c =新的E >();
^
test / TestClass.java:14:不兼容的类型
找到:test.TestClass.E >
必需:test.TestClass.E >
E > d =新E >();
^
4个错误

如果找到E<D<? extends C>>,那肯定应该匹配E<D<? extends Object>>,对吗?还是我错过了什么?

最佳答案

也许这可以帮助您了解:

    ArrayList<Object> aList = new ArrayList<String>();

这不会以类似的错误进行编译。

编辑:
向咨询:
http://www.ibm.com/developerworks/java/library/j-jtp01255.html

07-24 19:26
查看更多