Array vs ArrayList in Java
In Java, we have two ways to create an array.
Array
– Simple fixed sized arrays. We cannot change its size.ArrayList
– Is a class of Java Collections framework. It belongs tojava.util
package.
//Array int arr[] = new int[10]; //ArrayList - Here Type is the type of elements ArrayList<Type> arrL = new ArrayList<Type>();
Similarities
- Both are used for storing elements.
Array
andArrayList
both can store null values.- They both can allow duplicate values.
- Don’t maintain the order of elements.
Differences
Array | ArrayList |
---|---|
static in size. | Dynamic in size. |
fixed-length data structure | variable-length data structure. It can be resized itself when needed. |
It is mandatory to initializing the size of an array directly or indirectly. | Can create an instance of ArrayList without specifying its size. |
It performs fast in comparison to ArrayList because of fixed size. | ArrayList is internally backed by the array in Java. The resize operation in ArrayList slows down the performance. |
Stores both objects and primitives type. | It automatically converts primitive type to object. |
Use for loop or for each loop to iterate over an array. | Use for loop or for each loop or iterator to iterate over ArrayList . |
.length to get the length of an Array | size() method to determine the size. |
We can add elements in an array by using the assignment operator. eg: arr[0] = 0; | add() method to add elements in the ArrayList.eg: arrL.add(1); |
multi-dimensional. | Always single-dimensional. |
Example for Array in Java
public class ArrayFunction { public static void main(String[] args) { // creating an array of integer type int arr[] = new int[5]; // adding elements into array arr[0] = 12; arr[1] = 2; arr[2] = 15; arr[3] = 67; arr[4] = 12; System.out.println("Array Length: " + arr.length); for (int i = 0; i < arr.length; i++) { System.out.println("Index::" + i + " Value::" + arr[i]); } } }
Output
Array Length: 5 Index::0 Value::12 Index::1 Value::2 Index::2 Value::15 Index::3 Value::67 Index::4 Value::12
If you add a value for the index 5 it will throw java.lang.ArrayIndexOutOfBoundsException: 5
. This is fixed-length data structure.
It is mandatory to initializing the size of an array otherwise it will shows the error as
Variable must provide either dimension expressions or an array initializer.
Example for ArrayList in Java
public class ArrayListFunction { public static void main(String[] args) { //creating an instance of ArrayList ArrayList<Integer> list = new ArrayList<Integer>(); //adding element to arraylist list.add(12); list.add(34); list.add(56); list.add(78); //iteration over ArrayList using for-each loop for(Integer i:list) { System.out.println("Value: " + i); } } }
Output
Value: 12 Value: 34 Value: 56 Value: 78
Happy Learning 🙂