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>();



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>() {

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>(

Accessing, Altering and Deleting Elements from the Array List

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


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

Deleting an element from the list:


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++) {

or with the cleaner for-each loop:

 for (int num : numbersList) {