Sunday, November 18, 2012

Initialization of an ArrayList

When we declare and define a traditional array like this:

int [] x = new int [5];

The compiler creates an array of 5 integers and initializes them all to zero (which is the default initialization for integers).

But when we declare and define an ArrayList like this:

ArrayList<Integer> y = new ArrayList<Integer>(5);

Although the compiler sets aside the memory to hold 5 Integers, no actual Integers are created. Furthermore, not even pointers for these Integers are created (not even null pointers). Thus, if we try to print one of the elements, such as the first element in this ArrayList:

System.out.println(y.get(0));

The code will compile but a run time error of "ArrayIndexOutOfBounds" will be produced. That is because the ArrayList currently has a size of 0 (not 5) because no elements have been yet loaded into it.

Hopefully, this is clear.

Mr. Sarkar

No comments:

Post a Comment