public class Widgets<T> {
private final int SIZE = 100;
public void f(Object arg) {
/**
* Compile error:
* Cannot perform instanceof check against type parameter T.
* Use its erasure Object instead since further generic
* type information will be erased at runtime.
*/
if (arg instanceof T) { //Error
}
/**
* Compile error:
* Cannot instantiate the type T.
* Partly because of erasure, and partly the compiler cannot verify that
* T has a default (no-arg) constructor
*/
T var = new T(); // Error
/**
* Compile error:
* Cannot create a generic array of T.
*/
T[] array1 = new T[SIZE]; // Error
/**
* Compile warning:
* Type safety: Unchecked cast from Object[] to T[].
*/
T[] array2 = (T[]) new Object[SIZE]; //warning.
}
數(shù)組是協(xié)變的
package com.yxf.hellojava;
class Fruit {
}
class Apple extends Fruit {
}
class Jonathan extends Apple {
}
class Orange extends Fruit {
}
public class CovariantArrays {
public static void main(String[] args) {
// 創(chuàng)建一個Apple[]數(shù)組, 并將它賦給一個Fruit[]數(shù)組.
Fruit[] fruit = new Apple[10];
fruit[0] = new Apple();
fruit[1] = new Jonathan();
/**
* 1. 編譯器允許將一個Fruit對象放置到Fruit[]數(shù)組中,這是行的通的,因?yàn)閒ruit被聲明為一個Fruit[]的引用;
* 2. 在運(yùn)行時拋java.lang.ArrayStoreException異常,因?yàn)閒ruit引用真正指向的是Apple[]的對象.
*/
try {
fruit[2] = new Fruit();
} catch (Exception e) {
e.printStackTrace();
}
try {
fruit[3] = new Orange();
} catch (Exception e) {
e.printStackTrace();
}
}
}