Array data structure VS. ArrayList class

Array is a “legend” data type but ArrayList is part of the Collection framework. So what is the difference between them?

  1. ArrayList is “Resizable-array implementation of the List interface.” But array is fixed length.
  2. ArrayList.size() is a method call but array.length is internal variable
  3. Both support type safety: you have to specify data type when define it.
  4. ArrayList only support Object so no primitive type. This is due the List<E> is defined via generic type. Any primitive type is casted to corresponding object.

Now let look at a sample code to see some other difference:

package basic;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayListDemo {
	public static void main(String[] args){
		String[] str = new String[10];
		str[2] = "c";
		List<String> list = new ArrayList<String>(str.length);
		System.out.println("list1 size: " + list.size());
		System.out.println("list1 size: " + list.size());
//		list.add(2, "c");
		List<String> list2 = new ArrayList<String>();
		list2 = Arrays.asList(str);

Please note the line commented out. Even you create ArrayList with initial capacity. But the size is still 0! Following source code explains why:

    public ArrayList(int initialCapacity) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
        this.elementData = new Object[initialCapacity];

If you uncomment that line, you will get following exception:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 1
	at java.util.ArrayList.rangeCheckForAdd(
	at java.util.ArrayList.add(
	at basic.ArrayListDemo.main(

When you add element, the size will increase and make sure resize it:

    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;

This post doesn’t talk about performance. But here is what my judgment: in Java, always try to use Collection framework instead of raw date type like array. The reason is simple: you application especially commercial  software, will be built and improved by many iterations, so try to make it generic to adapt any change late. For example, defining an interface to accept and return List<E> will make your life much easier compare to Object[]. Performance is an overall evaluation not just a class.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s