Arraylist is an implementation of the list interface and it is a very widely used collection. ArrayList maintains the collection in the insertion order.
As the name suggest, the objects are arranged in an array. An array is a continuous allocation of memory where objects are stored.
The difference being, an arraylist is growable, i.e. the size of ArrayList is dynamic. It grows as we add elements to the ArrayList, With an Array we have to pre decide the size of the array but in case of ArrayList we do not have to set size beforehand.
As stated earlier, an ArrayList is growable, however we must be cautious in using ArrayList for large arrays. An ArrayList is initialized with a pre-decided size and once we add elements to list which grows beyond the list default size, java creates a new ArrayList with higher capacity and add the existing elements to the new array.
So if we know already the size of the list, it is preferable and more performant to initialize an ArrayList with an initial capacity
Below is an example of an empty ArrayList.
List<String> myList = new ArrayList<>();
Below is an example of an ArrayList with initial capacity of 100.
List<String> myList = new ArrayList<100>();
A collection is judged for insert, delete, retrieval performance. Some collections perform better in some areas over other. So before selection any collection, measure below parameter against your scenario at hand.
|Complexity||o(1) – o(n)||o(n)||o(1)|
As you can see, retrieval is really fast with ArrayList in all the scenarios.
Insert are fast when the list has spare capacity to add elements else it will have to copy the entire array to a new array to increase the capacity and then add the element, this process increases the insertion complexity to o(n).
Whereas Delete has the complexity of o(n).
Please comment if you would like to know more on ArrayList.