Many students have confusions between Array and ArrayList in Java when it comes to the question of which to use. The major difference between this two is the static nature of Array and dynamic nature of ArrayList. Specifically, if you define and initialize an Array, you can never add or remove elements from it. However, you can always make changes to the size of an ArrayList. Therefore, when you decide which to use, Array or ArrayList, the first thing you need to consider is whether you have a list of a fixed length or of a variable length. Now Let’s move on to how to initialize and define Array and ArrayList.
Initialize String array when you know all the elements:
If you want to make changes to one element of array (e.g. replace “red” with “orange”):
Initialize String array when you only know the number of elements:
Assign values to the array:
You can get the length of the array by animal.length().
Initialize ArrayList (Note: you cannot set initial size of an ArrayList):
Add elements to the ArrayList:
Get size of the ArrayList:
Remove the first element from the ArrayList:
Remove “Buffalo” from the ArrayList:
So when you decide whether to use Array or ArrayList, if you know the exact number of elements, use Array; if you don’t, use ArrayList.