Difference between Array and ArrayList
In Java, array and ArrayList are the well-known data structures. An array is a basic functionality provided by Java, whereas ArrayList is a class of Java Collections framework. It belongs to java.util package.
An array is a dynamically-created object. It serves as a container that holds the constant number of values of the same type. It has a contiguous memory location. Once an array is created, we cannot change its size. We can create an array by using the following statement:
The above statement creates an array of the specified size. When we try to add more than its size, it throws ArrayIndexOutOfBoundsException. For example:
Java ArrayList class
In Java, ArrayList is a class of Collections framework. It implements List<E>, Collection<E>, Iterable<E>, Cloneable, Serializable, and RandomAccess interfaces. It extends AbstractList<E> class.
We can create an instance of ArrayList by using the following statement:
ArrayList is internally backed by the array in Java. The resize operation in ArrayList slows down the performance as it involves new array and copying content from an old array to a new array. It calls the native implemented method System.arraycopy(sec, srcPos, dest, destPos, length) .
We cannot store primitive type in ArrayList. So, it stores only objects. It automatically converts primitive type to object. For example, we have create an ArrayList object,
The JVM converts it into Integer object through auto-boxing.
The following table describes the key differences between array and ArrayList:
Example of Array in Java
In the following example, we have simply created an array of length four.
12 2 15 67
Example of ArrayList in Java
In the following example, we have created an instance of ArrayList and performing iteration over the ArrayList.
12.4 34.6 56.8 78.9