![]() |
VOOZH | about |
In Java, both Array and ArrayList are used to store multiple elements of the same type, but they differ in structure and flexibility. An array has a fixed size, while ArrayList is dynamic and part of the Java Collections Framework, offering more built-in methods for easy data manipulation.
An Array is a fixed-size data structure used to store multiple elements of the same data type in contiguous memory locations. Each element is accessed using its index, starting from 0.
dataType[] arrayName; // Declaration
dataType[] arrayName = new dataType[size]; // Declaration and Creation
int[] numbers = {10, 20, 30, 40, 50}; // Declaration, Creation, and Initialization
ArrayList is a resizable implementation of the List interface in the Java Collections Framework that stores elements dynamically. It automatically grows or shrinks as elements are added or removed.
Note: ArrayList is a dynamic-size data structure in Java that can automatically grow or shrink as elements are added or removed. It is part of the Java Collections Framework.
ArrayList<String> list = new ArrayList<>();
The following common differences between Array and ArrayList are listed below with the help of examples.
Array uses the [] operator to access elements, whereas ArrayList uses methods such as get(), add(), and remove().
1 1
Array has a fixed size, whereas ArrayList is dynamic and can grow or shrink as needed.
[1, 2, 3, 4] [1, 2, 3]
Array supports both primitive data types and objects, whereas ArrayList supports only objects.
Note: When we do arraylist.add(1) than it converts the primitive int data type into an Integer object which is as illustrated in below example.
Successfully compiled and executed
| Feature | Array | ArrayList |
|---|---|---|
| Dimensionality | Can be single-dimensional or multi-dimensional. | Supports only single-dimensional structures. |
| Traversing Elements | Uses for loop and enhanced for-each loop. | Uses for, for-each, Iterator, and ListIterator. |
| Length / Size | Uses the length property to get the size. | Uses the size() method to get the number of elements. |
| Size Nature | Fixed size; cannot be changed after creation. | Dynamic size; can grow or shrink automatically. |
| Performance | Faster due to fixed size and direct memory access. | Slightly slower because of dynamic resizing and additional operations. |
| Primitive Data Support | Stores both primitive data types and objects. | Stores only objects (wrapper classes are used for primitives). |
| Generics Support | Does not support generics. | Supports generics, providing type safety. |
| Adding Elements | Elements are added using index assignment (arr[0] = value). | Elements are added using the add() method. |