public class Fruits<T> {
private List<T> array=
new ArrayList<T>();
public void add(T f){
array.add(f);
}
public T
get(
int index){
return array.
get(index);
}
}
以上代码得到了数组类型,而且类型安全由泛型提供
public class FruitsReference {
static Fruits<Integer>[] f;
class Fruits<T>{}
}
以上代码不会报错和产生任何警告,但永远不能创建这个确切类型的数组
public class Fruit1 {
static final
int SIZE=
100;
static Fruits<Integer>[] f;
@SuppressWarnings(
"unchecked")
public static void main(String[] args){
f=(Fruits<Integer> [])
new Fruits[SIZE];
System.
out.println(f.getClass().getSimpleName());
f[
0]=
new Fruits<Integer>();
}
}
转型信息只存在于编译期,在运行时数组f依然是Object数组
public class FruitsArray<T> {
private T[] array;
@SuppressWarnings(
"unchecked")
public FruitsArray(
int sz){
array=(T[])
new Object[sz];
}
public void put(
int index,T item){
array[index]=item;
}
public T
get(
int index){
return array[index];
}
public T[]
rep(){
return array;
}
public static void main(String[] args){
FruitsArray<Integer> fa=
new FruitsArray<Integer>(
10);
Object[] of=fa.rep();
}
}
不能用Integer[]来捕获array,因为在运行时类型是Object[].
public class FruitsArray<T> {
private T[] array;
@SuppressWarnings(
"unchecked")
public FruitsArray(
int sz){
array=(T[])
new Object[sz];
}
public void put(
int index,T item){
array[index]=item;
}
public T
get(
int index){
return (T)array[index];
}
public T[]
rep(){
return (T[])array;
}
public static void main(String[] args){
FruitsArray<Integer> fa=
new FruitsArray<Integer>(
10);
Object[] ofu=fa.rep();
}
}
成功创建泛型数组的唯一方式是创建一个被擦除类型的新数组,然后将其转型。
public class FruitsArray<T> {
private T[] array;
@SuppressWarnings(
"unchecked")
public FruitsArray(Class<T> type,
int sz){
array=(T[])
new Object[sz];
}
public void put(
int index,T item){
array[index]=item;
}
public T
get(
int index){
return array[index];
}
public T[]
rep(){
return array;
}
public static void main(String[] args){
FruitsArray<Integer> fa=
new FruitsArray<Integer>(Integer.class,
10);
Integer[] ifu=fa.rep() ;
}
}
类型标记Class< T >被传递到构造器中,就可以从擦除中恢复