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";
		System.out.println(str);
				
		List<String> list = new ArrayList<String>(str.length);
		System.out.println("list1 size: " + list.size());
		list.add("a");
		System.out.println("list1 size: " + list.size());
//		list.add(2, "c");
		System.out.println(list);
		
		List<String> list2 = new ArrayList<String>();
		list2 = Arrays.asList(str);
		if(list2.equals(list2)){
			System.out.println("Equal");
		}
		
	}
}

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) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        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(ArrayList.java:643)
	at java.util.ArrayList.add(ArrayList.java:455)
	at basic.ArrayListDemo.main(ArrayListDemo.java:17)

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.

Reference:

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s