Arraylist vs. Array

ARRAYLIST and ARRAY are quite alike but in the same way very unlike. They can both keep data in a structure which you can walk through in different ways but the ArrayList is a bit more dynamic in how we can use it.

An Array is always declared with a static amount of data. In the example below we create an Array named myNumbers with space to hold three integers.

int[] myNumbers = new int[3];

UPON CREATION they will all be set to 0 so actually they exist directly after creation. If we try to access or add a fourth integer to this Array we would get an ArrayIndexOutOfBoundsException. You might think that all we need to do is to declare same myNumbers with more then three spaces for integers but if you do this the old myNumbers will be erased and a new created with more space.

int[] myNumbers = new int[4]; /* this would completly erase the
old myNumbers-array, creating a new one */

So if we would like to have the strength of an Array but feel that what we usually can do with it is to less we can as of Java 1.5 or later use an ArrayList. The declaration for an ArrayList look like this.

ArrayList name = new ArrayList();

THE CLASS should be what kind of variable you would like to store in the ArrayList, if you do not use any class here any object can be saved. Using no class at all is the same as using Object, i.e any object can be saved.

ArrayList myNumbers = new ArrayList(); /* can hold Integers only */
ArrayList collection = new ArrayList(); // can hold any object

When we have an ArrayList created we can use some built in functionallity to handle it. I will give short examples below in a code-snippet.

ArrayList myNumbers = new ArrayList(); /* can hold Integers only */
myNumbers.add(10); // adds the number 10 to the list
myNumbers.add(10,1); /* adds the number 10 to second element in
the list due to the fact that the first element have index 0 */
myNumbers.get(0); // get the first element from the list
myNumbers.size(); /* returns the number of elements in list,
in our case 2 */
myNumbers.isEmpty(); // true if empty
int myCheckedNumber = 10;
myNumbers.contains(myCheckedNumber); /* returns true if 10 is
within the list */
System.out.println(myNumbers); /* would print "[10,10]" in
console */

WORTH TO REMEMBER is that an Array with n elements would only need about 4*n bytes of memory. If we use an ArrayList for the same n elements would require about 20*n bytes of memory. The reason for this is that the ArrayList is an array of objects as well as an array of references. Due to this fact we always should use Array if we know how many elements we will need and memory is an issue for us. ArrayList should in this aspect only be used in cases where we need functionallity from it.

Leave a Reply

Your email address will not be published. Required fields are marked *