Skip to main content

ArrayList in Java

Array lists are an alternative to arrays in Java. The main difference is that array lists are not fixed in size and do not receive a number of elements to hold. Therefore, elements can be added to an array lists and deleted from it.

Declaring and Initializing an Array List

Important is to import ArrayList from the package java.util, which is available by default.

import java.util.ArrayList;

public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();

numbers.add(1);
numbers.add(2);
numbers.add(3);

}
}

Instead of adding the elements to the empty list, you can initialize the list right away: (You need to import java.util.Arrays in order for this to work)

ArrayList<Integer> numbers = new ArrayList<Integer>(
Arrays.asList(1, 2, 3)
);

There is even a third way:

ArrayList<Integer> numbers = new ArrayList<Integer>() {
{
add(1);
add(2);
add(3);
}
};

Initializing an Array List from an Array

The above shown method Arrays.asList() can be used to get an array list based on an array: (Don't forget to import java.util.Arrays)

Integer[] numbers = {1, 2, 3};

ArrayList<Integer> numbersList = new ArrayList<Integer>(
Arrays.asList(numbers)
);

Accessing, Altering and Deleting Elements from the Array List

Accessing an element, for example in order to print it, can be done with get():

numbersList.get(0)

0 is the index of the first element in the list.

Deleting an element from the list:

numbersList.reomve(index)

When deleting from an array list, the size is reduced. Therefore, there is no empty space in the list left.

In a similar way, we can overwrite values at a given position:

numbersLits.set(index, newValue)

Looping over the Array List

Iterating can be done with a class for-loop:

for (int i = 0; i < numbersList.size(); i++) {
System.out.println(numbersList.get(i));
}

or with the cleaner for-each loop:

 for (int num : numbersList) {
System.out.println(num);
}