Array vs ArrayList in java
There are a lot of articles on this topic. however, I also want to share what I have learnt and understood from Head First Java with you. Knowing the differences and similarities between Array and ArrayList helps to decide when you can use Array and ArrayList.
As you know already Array and ArrayList is an important data structure in java. The fundamental difference between them is the size.
The array is static in size, the size of the array should be decided when it is declared and can not be changed later by adding more elements at the same time the size of the ArrayList can be changed dynamically when we add or remove an object from an ArrayList.
Java provides Array with basic functionality While ArrayList is a class that comes from the collection framework and is internally based on Array.
And, Array can contain both primitives and objects based on the definition of the array but each element of an array is considered as a primitive variable and objects and even the Array also is an object, while elements of ArrayList are considered objects, these objects have states and behaviours like other class objects. Therefore it is able to do more functions on its objects.
We have to use assign operates to put elements in an array, The location will be indicated by the index, the index of the first element is zero.This is common for Array and ArrayList.If you assign outside the boundaries, java will throw an exception named ArrayIndexOutOfBoundsException.Whereas java provides add() method to put elements into ArrayList
Let's see some code snippets for the difference between Array and ArrayList by using coding for general actions.
At the same time, They both have some similarities such as, both can contain null values and duplicate elements.
However, java provides support to change the array to ArrayList and vice versa. To convert from an Array to an ArrayList, use the Array.asList() method and to convert from an ArrayList to an Array, use the toArray() method.