In this post, we will discuss the difference between an array and ArrayList in Java.
An Array is a fixed size data structure that does not permit elements to be inserted or removed after its creation. It is possible to effectively implement a dynamic version of an array by reallocating storage and copying the elements of the old array to it. This is exactly how an ArrayList works which is resizable-array implementation of the List interface.
Common operations (such as get, set for ArrayList and store, select for Arrays) takes constant time. However, an array doesn’t support insertion operation while insertions at the end of the ArrayList require only amortized constant time i.e. adding n elements requires
Arrays in Java can hold both primitives datatypes (int, char, long, float, double, boolean, etc) and Java objects (Integer, Character, Long, Float, Double, Boolean, String, etc) while an ArrayList can hold only Java objects.
O(n) space for n number of elements and do not reserve any additional storage while an ArrayList reserve linear
O(n) additional storage. We can call
trimToSize() method of ArrayList class to minimize the storage of an ArrayList instance.
The size of the ArrayList can be calculated by its
size() method while we can use
length variable to calculate length of an array.
The dimension of an array is the number of indices needed to select an element. Arrays in Java supports one-dimensional array, two-dimensional array, three-dimensional array and so on.. while an ArrayList has no concept of dimentions but we can easily construct an ArrayList of ArrayLists or ArrayList of ArrayList of ArrayLists.
7. Generics support
Generics are not supported by an array but it can be use with an ArrayList to ensure type safety.
References: Arrays Wiki
Thanks for reading.