Java:generic类中数组的wierd问题

Java:generic类中数组的wierd问题,java,Java,我可以这样做: public class className { public static void main(String[] args){ Storage<Book> bookstorage = new Storage<Book>(100); } public class Storage<E> implements GenStorage<E>{ private int size; private E [] array = (E

我可以这样做:

public class className {
public static void main(String[] args){

    Storage<Book> bookstorage = new Storage<Book>(100);

}

public class Storage<E> implements GenStorage<E>{

private int size;
private E [] array = (E[]) new Object[100];

public Hylle(int size){
    this.size = size;
    for (int i = 0; i<size; i++){
        array[i] = null;
    }
}
公共类类名{
公共静态void main(字符串[]args){
存储书籍存储=新存储(100);
}
公共类存储实现了GenStorage{
私有整数大小;
私有E[]数组=(E[])新对象[100];
公共海勒(内部尺寸){
这个。大小=大小;

for(int i=0;i数组对象不会自动扩展其大小。这就是为什么他们在数组大小更改时引入了ArrayList。我可能建议您尝试使用ArrayList来避免此问题。

字段初始值设定项在构造函数体之前执行。在第二个示例中:

private int size;
private E [] array = (E[]) new Object[size];
创建大小为0的数组,因为这是int的默认值。然后:

for (int i = 0; i < size; i++){
    array[i] = null;
}
for(int i=0;i
将尝试索引到大小为0的数组中,导致出现
ArrayIndexOutOfBoundsException


第二个示例之所以有效,是因为您显式地将其大小设置为100。因此,在这两个示例中,传入构造函数的大小实际上从未用于初始化数组。

因为您在构造函数外部初始化成员变量。此类初始化发生在超级构造函数之间和构造函数之前当前类的tor。这意味着引擎盖下的构造函数类似于:

public Hylle(int size){
    // super constructor
    super();
    // out constructor initialization
    this.size = 0;
    this.array = (E[]) new Object[size]; // which is 0
    // this constructor
    this.size = size;
    for (int i = 0; i<size; i++){
        array[i] = null;
    }
}
public Hylle(整数大小){
//超级构造函数
超级();
//out构造函数初始化
此值为0.size=0;
this.array=(E[])新对象[size];//它是0
//这个构造函数
这个。大小=大小;

对于(inti=0;我只是一个旁注:看看java中的泛型数组创建。您很快就会在代码中遇到一些严重的问题。
for (int i = 0; i < size; i++){
    array[i] = null;
}
public Hylle(int size){
    // super constructor
    super();
    // out constructor initialization
    this.size = 0;
    this.array = (E[]) new Object[size]; // which is 0
    // this constructor
    this.size = size;
    for (int i = 0; i<size; i++){
        array[i] = null;
    }
}