一、数组与列表容器的比较
①、协变与不可变类型:
数组:是协变类型的。协变的意思就是Number是Integer的父类,那么Number[] data = new Integer[]; 是成立的。
列表:是不可变类型。就是说无法List<Number> list = new List<Integer>();
无法发生协变才是正确的方式。原因:
public static void main(String[]args){
Object[] obj = new Long[10];
obj[0] = "Is right";
//运行时候报错:java.lang.ArrayStoreException
List<Object> data = new ArrayList<String>();
//直接报错
}
②、运行时检验与编译器检验。
数组:运行时检验。因为数组在编译使其创建的类是具体化的。然后在运行期间检验类型约束是否正确。所以就会产生将String类添加到Long类型的数组中会在运行时报java.lang.ArrayStoreException的错误。感觉这个模式是特定针对数组的协变而创造的,因为数组在编译器中也是会受检验报错的。比如说:
public static void main(String[]args){
Integer[] data = new Integer[10];
data[0] = 3.14;//在编译器直接报错
}
泛型:编译期检验。因为泛型会在运行的过程中参数类型会被擦除,所以必须在编译期就得保证类型安全。这就不容许有协变这个性质。
二、数组与泛型无法结合使用
数组与泛型的结合:
new List<String>[]、new E[] 都是错误的。
因为数组是在运行期检验的,但是运行期间泛型会被擦除,从而导致Java虚拟机无法判断类型的安全性。
同时由于数组是运行期检验,所以具有协变的特性。这也导致了泛型无法与数组结合。
例:
public static void main(String[]args){
List<String> strList = new ArrayList<String>();
List<Integer> intList = new ArrayList<Integer>();
List<String>[] strArray = new List<String> [10];//假设允许泛型数组
List<Integer>[] intArray = new List<Integer>[10];
Object[] obj = strArray;
obj[0] = intList; //将intList存入了strArray中。 与刚才的协变的例子是一样的
List<String> str = strArray[0].get(0);
}
从技术上来说,泛型是不可具体化的。
不可具体化:运行期间虚拟机获得的信息不能够比编译期间更多(擦除导致的问题)。
只有通过无限通配符(?)才能让泛型变为具体化
由于这一特性,导致使用泛型的数组(T[] a)和利用泛型转型((T) a)是类型不安全的,因为虚拟机根本不知道转化成那种类型。
所以对泛型使用可变参数列也是不安全的。
例:
public class Test <E> {
//产生不安全的警告
public void get(E ... dataEs){
}
}
例如:现有有一个方法通过其他方法操纵数组的四则运算。
//假设进行加法运算。
public int handleList(List<E> list,Function<E> function,int initalVal){
E[] datas = (E[])list.toArray(); //类型不安全的警告。
int result = initalVal;//初始数据
for(E data : datas){
result = function.apply(result,data);
}
return result;
}
为了消除这种安全警告,只能用上注解。但是如果使用上了列表容器就能够直接消除警告了
public int handleList(List<E> list,Function function,int initalVal){
List<E> datas = new ArrayList<E>(list);//消除警告
int result = initalVal;//初始数据
for(E data : datas){
result = function.apply(result,data);
}
return result;
}
所以说,尽量使用列表。但是如果必须使用数组来提高效率的话,只有加上注解这一个方法。