Java: A Complete Guide to Array and ArrayList

  • Post author:
  • Post category:Java

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:

1

If you want to make changes to one element of array (e.g. replace “red” with “orange”):

2

Initialize String array when you only know the number of elements:

3

Assign values to the array:

4

You can get the length of the array by animal.length().

Initialize ArrayList (Note: you cannot set initial size of an ArrayList):

Screenshot (72)

Add elements to the ArrayList:

8

Get size of the ArrayList:

9

Remove the first element from the ArrayList:

Screenshot (75)

Remove “Buffalo” from the ArrayList:

10

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.