http://bbs.tianya.cn/post-free-6148377-1.shtml
package com.example.genericparadigmdemo.paradigm.array;
public class A {
}
package com.example.genericparadigmdemo.paradigm.array;
public class B extends A{
}
package com.example.genericparadigmdemo.paradigm.array;
public class C extends B {
}
package com.example.genericparadigmdemo.paradigm.array;
public class ArrayUtil {
public static <T> T getMiddle(T... a){
return a[a.length/2];
}
public static void main(String[] args) {
String middleStr = ArrayUtil.<String>getMiddle("你好", "在家", "无故");
System.out.println("middleStr:"+middleStr);
Integer middleInte = ArrayUtil.getMiddle(1, 2, 3);
System.out.println("middleInte:"+middleInte);
}
}
package com.example.genericparadigmdemo.paradigm.array;
public class Father {
public B f1(B obj){
System.out.println("Father.f1()");
return new B();
}
}
package com.example.genericparadigmdemo.paradigm.array;
public class Son extends Father {
/**
* 返回值可以是B也可以是C
* @param obj
* @return
*/
@Override
public C f1(B obj){
System.out.println("Son.f1()");
return new C();
}
}
package com.example.genericparadigmdemo.paradigm.array;
import java.util.ArrayList;
/**
* 其中B类继承于A类
*/
public class TestAB {
public static void main(String[] args) {
ArrayList<B> list1 = new ArrayList<>();
list1.add(new B());
/**
* 编译error 需要A,but found B
*/
//ArrayList<A> list2 = list1;
/**
* 协变,指定了上界
*/
ArrayList<? extends A> list3 = new ArrayList<B>();
/**
* 逆变,指定了下界
*/
ArrayList<? super B> list4 = new ArrayList<A>();
}
}
package com.example.genericparadigmdemo.paradigm.array;
import java.util.ArrayList;
import java.util.Collections;
public class TestArrayAndList {
public static void main(String[] args) {
/**
* compile error
* 需要Abut 声明传入B
*/
//B[] r1 = test(new ArrayList<B>());
/**
* 尽管接受类型是A[] but传入还是B的,编译异常
*/
//A[] r2 = test(new ArrayList<B>());
/**
* 如果test接受的是Object,则以上包括这个就不会
* 编译异常了
*/
//Object[] r3 = test(new ArrayList<Object>());
A[] r4 = test(new ArrayList<A>());
Object[] r5 = test(new ArrayList<A>());
}
public static A[] test(ArrayList<A> list){
return new A[1];
}
}
package com.example.genericparadigmdemo.paradigm.array;
public class TestFatherSon {
public static void main(String[] args) {
Father foo = new Son();
foo.f1(new B());
}
}