Here you will learn about difference between array and arraylist in java.
Both array and arraylist are most important and frequently used data structure in java. Below I have discussed about various differences between them.
Difference between Array and ArrayList in Java
Property | Array | ArrayList |
Size | Array is fixed in size. Once declared, its size can’t be changed. | ArrayList size can be changed after declaration. For example when we add or remove element in arraylist, its size increases or decreases accordingly. |
Primitives | Array can contain primitive data types as well as objects. | ArrayList can contain objects only. When we try to add a primitive type element in arraylist then the element is first converted into its corresponding wrapper class and then added. This process of conversion is called auto-boxing. |
Performance | Array provides better performance and uses less memory. | ArrayList performance is less and uses more memory as compared to Array. ArrayList internally uses dynamic array for storing elements. Each time an element is added or removed, a new array is created. |
Element Type | Array can contain elements of same type. | ArrayList can contain elements of different types. |
Iteration | We can iterate through array using loops only. | ArralyList provides various ways for iteration like loops, Iterator and ListIterator class. |
Dimension | Array can be single as well as multi-dimensional. | ArrayList is only single dimensional. |
Storage | Array elements are stored at contiguous memory locations. | ArrayList elements are not stored at contiguous memory locations. |
Array and ArrayList Example in Java
Here I have shared one example that will help you to understand the working of array and arraylist.
import java.util.ArrayList; import java.util.Iterator; public class ArrayvsArrayList { public static void main(String...s){ //Array int arr[] = new int[3]; arr[0] = 10; arr[1] = 15; arr[2] = 20; for(int i=0;i<arr.length;++i){ System.out.print(arr[i]+" "); } System.out.println("\n"); //ArrayList ArrayList<Integer> arrl = new ArrayList<Integer>(); arrl.add(10); //auto-boxing arrl.add(15); //auto-boxing arrl.add(20); //auto-boxing Iterator it = arrl.iterator(); while(it.hasNext()){ System.out.print(it.next()+" "); } } }
Output
10 15 20
10 15 20
Comment below if you found anything incorrect in above tutorial for difference between array and arraylist in java.