5 Minutes of Java (11. Array vs ArrayList)

Standard Java Array has a fixed length. So after it is created, it cannot grow or shrink,  which means that you must decide in advance how many elements an array should hold.

ArrayList has a variable size, therefore you need not specify its size at the point of the creation. Therefore it is more friendly to use than the array.

Declaration and Creation

Array:
dataType[] arrayRefVar = new dataType[arraySize];

Example:

String[] arrayA = new String[5];

Alternatively you can create arrays as follows if you know the values to put in:

dataType[] arrayRefVar = {value0, value1, ..., valuek};

Example:

String[] arrayB = {"Bentley", "Wilson", "Palmer", null, null};
ArrayList:
ArrayList<dataType> arrayListRefVar = new ArrayList<dataType>();

<dataType> decides what can be stored inside the ArrayList.

Example:

ArrayList<String> listA = new ArrayList<String>();

 Common Operations:

Operation
Array
ArrayList
Get size
arrayA.length
listA.size()
get the element at position i
arrayA[i]
listA.get(i)
Replace the element at position i
arrayA[i] = “newValue”;
listA.set(i,”newValue”);
Delete the element at position i
arrayA[i] = null;
listA.remove(i);
Append an element to the end
NA
listA.add(“newValue”);
Insert an element at position i
NA
listA.add(i,”newValue”);