-1

I can do this:

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;
    }
}

while this gives me an ArrayIndexOutOfBoundsException:

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

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

public Hylle(int size){
    this.size = size;
    for (int i = 0; i<size; i++){
        array[i] = null;
    }
}

The program runs while the size of the array is equal too or greater than the set size of the object. Why does this happen, and how can I fix it? Thank you in advance.

Edit: Fixed it, I just had to do this:

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

private int size;
private E [] array;

public Hylle(int size){
    this.size = size;
    array = (E[]) new Object[size];
    for (int i = 0; i<size; i++){
        array[i] = null;
    }
}
Henrik Klev
  • 322
  • 1
  • 11
  • 1
    Just a sidenote: take a look at generic array-creation in java. You'll encounter some serious problems with that code pretty soon. –  Feb 05 '16 at 03:15

3 Answers3

2

The field initializer is executed before the constructor body. In your second example:

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

Creates an array of size 0 because that is the default value of an int. Then:

for (int i = 0; i < size; i++){
    array[i] = null;
}

Will try to index into an array of size 0 causing an ArrayIndexOutOfBoundsException.

The second example works because you are explicitly setting its size to 100. So the size you pass into the constructor is actually never used to initialize the array in both examples.

George Mulligan
  • 11,813
  • 6
  • 37
  • 50
0

Array Object does not Extend its size automatically. That's why they introduced ArrayList where the size of the array changes. I might advice you to try using ArrayList to avoid this issue.

KRam1802
  • 31
  • 1
  • 11
0

Because you are initializing member variables outside the constructor. Such initializations happens in-between the super constructor and before the constructor of the current class. Which means that your constructor under the hood is something like:

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;
    }
}

It's easy to see that the array is created with 0 size.

Jack
  • 131,802
  • 30
  • 241
  • 343