public class Info { private T msg; public Info(T msg) { this.msg = msg; } public T getMsg() { return msg; } public void setMsg(T msg) { this.msg = msg; }}public class GenDemo { public static void main(String[] args) { Info info0 = new Info(1) ; // 没有指定泛型类型,但写代码时会有警告 Info
public abstract class Shape { public abstract void draw(Canvas c); } public class Circle extends Shape { private int x,y,radius; public void draw(Canvas c) { ... } } public class Rectangle extends Shape { private int x,y,width,height; public void draw(Canvasc) { ... } }
List shapes = new ArrayList ();List cicleSupers = shapes;cicleSupers.add(new Cicle()); //OK, subclass of Cicle also OKcicleSupers.add(new Shape()); //ERROR
Object[] oa = new Object[100]; Collectionco = new ArrayList(); fromArrayToCollection(oa, co);// T inferred to be Object String[] sa = new String[100]; Collection cs = new ArrayList (); fromArrayToCollection(sa, cs);// T inferred to be String fromArrayToCollection(sa, co);// T inferred to be Object Integer[] ia = new Integer[100]; Float[] fa = new Float[100]; Number[] na = new Number[100]; Collection cn = new ArrayList (); fromArrayToCollection(ia, cn);// T inferred to be Number fromArrayToCollection(fa, cn);// T inferred to be Number fromArrayToCollection(na, cn);// T inferred to be Number fromArrayToCollection(na, co);// T inferred to be Object fromArrayToCollection(na, cs);// compile-time error
public void go(T t) { System.out.println("generic function"); } public void go(String str) { System.out.println("normal function"); } public static void main(String[] args) { FuncGenric fg = new FuncGenric(); fg.go("haha");//打印normal function fg. go("haha");//打印generic function fg.go(new Object());//打印generic function fg. go(new Object());//打印generic function }
/*代码一:编译时错误*/ public class Erasure{ public void test(int i){ System.out.println("Sting"); } public int test(int i){ System.out.println("Integer"); } }
示例2:
/*代码二:正确 */ public class Erasure{ public void test(List ls){ System.out.println("Sting"); } public int test(List li){ System.out.println("Integer"); } }
List [] lsa = new ArrayList [10]; //compile error.
因为如果可以这样,那么考虑如下代码,会导致运行时错误.
示例:
List [] lsa = new ArrayList [10]; // 实际上并不允许这样创建数组 Object o = lsa; Object[] oa = (Object[]) o; List li = new ArrayList (); li.add(new Integer(3)); oa[1] = li;// unsound, but passes run time store check String s = lsa[1].get(0); //run-time error - ClassCastException
List [] lsa = new List [10]; // ok, array of unbounded wildcard type Object o = lsa; Object[] oa = (Object[]) o; List li = new ArrayList (); li.add(new Integer(3)); oa[1] = li; //correct String s = (String) lsa[1].get(0);// run time error, but cast is explicit Integer it = (Integer)lsa[1].get(0); // OK