其实一句话就是:
super最好用来作为输出参数,extends最好用来作为输入参数;
看看下面的例子:
private class A { // } private class B extends A { // } private class C extends B { // } public void test() { List<? super B> test = new ArrayList(); test = new ArrayList<A>(); test = new ArrayList<B>(); test = new ArrayList<C>(); //不能接受比B还小的类 A a = test.get(0);//不能get B b = test.get(0);//不能get C c = test.get(0);//不能get test.add(new A());//但是不能add比B大的类 test.add(new B()); test.add(new C()); List<? extends B> test1 = new ArrayList(); test1 = new ArrayList<A>();//不能接受比B大的类 test1 = new ArrayList<B>(); test1 = new ArrayList<C>(); A a1 = test1.get(0); B b1 = test1.get(0); C c1 = test1.get(0);//但是不能get比B小的类 test1.add(new A());//不能add test1.add(new B());//不能add test1.add(new C());//不能add }
下面是在Eclipse中的编译错误截图:
具体的原因可以参见:
http://stackoverflow.com/questions/4343202/difference-between-super-t-and-extends-t-in-java
http://docs.oracle.com/javase/tutorial/java/generics/capture.html
时间: 2024-10-13 07:26:51