标题: 泛型数组?? [打印本页] 作者: 邵中国 时间: 2012-3-31 14:10 标题: 泛型数组?? import java.util.*;
public class Array<T>
{
private T[] array;
@SuppressWarnings("unchecked")
public Array(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)
{
Array<Integer> ga = new Array<Integer>(10);
Integer[] ia = ga.rep();
System.out.println(ia.length);
}
}
错误提示:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; can
not be cast to [Ljava.lang.Integer;
at Array.main(Array.java:25) 作者: H07000223 时间: 2012-3-31 17:46
所谓泛型的作用范围就是在编译期,控制数据类型。
当你运行的时候就这些“类型”信息自动去除。
在java中,不能通过直接通过T[] tarr=new T[10]的方式来创建数组,最简单的方式便是通过Array.newInstance(Class<t>type,int size)的方式来创建数组
例如下面的程序。
public class ArrayMaker<T> {
private Class<T> type;
public ArrayMaker(Class<T> type) {
this.type = type; }
@SuppressWarnings("unchecked")
T[] createArray(int size) {
return (T[]) Array.newInstance(type, size);
}
List<T> createList() {
return new ArrayList<T>();
} /** * @param args */
public static void main(String[] args) {
/* * Even though kind is stored as Class<T> , erasure means that it is actually just being stored as a Class, with
* no parameter. So, when you do some thing with it, as in creating an array, Array.newInstance( ) doesn’t
* actually have the type information that’s implied in kind; so it cannot produce the specific result, wh ich
* must therefore be cast, which produces a warning that you cannot satisfy.
*/
ArrayMaker<Type> am2 = new ArrayMaker<Type>(Type.class);
System.out.println(Arrays.asList(am2.createArray(10))); System.out.println(Arrays.asList(am2.createList()));
}
}
class Type {
@Override
public String toString() {
return "type";
}
}