最近我们讲过了java中的一个比较特殊的数组,它的名字叫泛型数组。有的人对于这种数组的类型产生了好奇,首先可以在这种明确的是,它是属于强制转换类型的一种。那么在具体的转换过程中,又会存在着一些不可避免的问题。下面我们就java泛型数据的转换带来详解。
1、转换说明
因为泛型,当取得数组中每个元素时People p = peopleGenericArray.get(0),不需要显式进行向下的强制类型转换。同样因为泛型,当获取数组对象时,并不会明确地向下转换类型,但是为什么运行时会发生类型匹配异常,这是因为没有先进行向上类型转换。总结:在泛型数组中发生的强制类型转换
2、实例package hash;
import sort.People;
/**
* Created with IntelliJ IDEA.
* User: ASUS
* Date: 14-9-12
* Time: 下午5:12
* To change this template use File | Settings | File Templates.
*/
public class GenericArray {
private final T[] items;
public GenericArray(int size) {
items = (T[]) new Object[size];
}
public void put(int index, T t) {
items[index] = t;
}
public T get(int index) {
return items[index];
}
public T[] getItems() {
return items;
}
public static void main(String args[]) {
GenericArray peopleGenericArray = new GenericArray(5);
peopleGenericArray.put(0, new People(12, "12323"));
peopleGenericArray.put(1, new People(12, "12323"));
peopleGenericArray.put(2, new People(12, "12323"));
peopleGenericArray.put(3, new People(12, "12323"));
People p = peopleGenericArray.get(0);
System.out.println(p);
System.out.println("sddddddddddddddd");
try {
People[] peoples = peopleGenericArray.getItems(); //这行代码会出现ClassCastException异常
for (People people : peoples) {
System.out.println(people);
}
} catch (Exception e) {
e.printStackTrace();
}
try {
Object[] objects = peopleGenericArray.getItems();
for (Object object : objects) {
System.out.println(object);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
泛型数组的类型信息会被擦除,且在运行的过程中数组的类型有且仅有Object[],如果我们强制转换成T[]类型的话,虽然在编译的时候不会有异常产生,但是运行时会有ClassCastException抛出。因为在程序运行过程中仅存在这Object[]类型的数组,所以类型转换过程中要使用Object[]。。。而不能使用People[],虽然编译过程不会出现错误。
以上就是java泛型数组的转换类型,相信这个知识点,很多人还是第一次接触到。对于文章中不太能理解的地方,可以反复进行阅读。更多Java学习指路: