Skip to content

ArrayList in Java, with Examples

Learn how to use ArrayList in Java: add, remove and iterate elements, store objects, and work with nested ArrayLists, with practical examples.

The ArrayList class in Java lets you store data in memory in a way similar to Arrays, with the advantage that the number of elements it holds grows dynamically, meaning you don’t need to declare its size as you do with Arrays. For all of you who have studied data structures like Stacks, Queues, Lists, Trees (AVL, B, B+, B*), etc. in a course, I have to say that ArrayLists "throw out the window" all the theory behind those data structures, since ArrayLists let us add, remove and modify elements (which can be objects or atomic elements) transparently for the developer. Before explaining how to work with ArrayLists, here is a link to the JavaDoc, just click HERE.

First of all, you can download the code of all the examples below by clicking HERE.

The main methods for working with ArrayLists are the following:


// Declaration of an ArrayList of "String". It can be of any other Element or Object (float, Boolean, Object, ...)
ArrayList<String> nombreArrayList = new ArrayList<String>();
// Adds the element to the ArrayList
nombreArrayList.add("Elemento");
// Adds the element to the ArrayList at position 'n'
nombreArrayList.add(n, "Elemento 2");
// Returns the number of elements in the ArrayList
nombreArrayList.size();
// Returns the element at position '2' of the ArrayList
nombreArrayList.get(2);
// Checks whether the element ('Elemento') passed as a parameter exists
nombreArrayList.contains("Elemento");
// Returns the position of the first occurrence ('Elemento') in the ArrayList  
nombreArrayList.indexOf("Elemento");
// Returns the position of the last occurrence ('Elemento') in the ArrayList   
nombreArrayList.lastIndexOf("Elemento");
// Removes the element at position '5' of the ArrayList   
nombreArrayList.remove(5); 
// Removes the first occurrence of the 'Elemento' passed as a parameter.  
nombreArrayList.remove("Elemento");
//Removes all elements from the ArrayList   
nombreArrayList.clear();
// Returns True if the ArrayList is empty. Otherwise returns False   
nombreArrayList.isEmpty();  
// Copy an ArrayList 
ArrayList arrayListCopia = (ArrayList) nombreArrayList.clone();  
// Converts the ArrayList to an Array 
Object[] array = nombreArrayList.toArray();   

Another very important thing when working with ArrayLists is "Iterators" (Iterator). Iterators are used to traverse ArrayLists and work with them. Iterators have only three methods: "hasNext()" to check whether there are still elements left in the iterator, "next()"  to give us the next element of the iterator; and "remove()", which removes the element from the Iterator.

Okay, if this isn’t totally clear yet, let’s go through the first example. In the following snippet, we declare an ArrayList of Strings and fill it with 10 Strings (Elemento i). We do this with the "add()" method. Then we add a new element to the ArrayList at position '2' (with the method "add(position,element)"), which we’ll call "Elemento 3", and afterwards we’ll print the contents of the ArrayList by traversing it with an Iterator. The snippet looks like this:


// Declaración el ArrayList
ArrayList<String> nombreArrayList = new ArrayList<String>();

// Añadimos 10 Elementos en el ArrayList
for (int i=1; i<=10; i++){
	nombreArrayList.add("Elemento "+i); 
}

// Añadimos un nuevo elemento al ArrayList en la posición 2
nombreArrayList.add(2, "Elemento 3");

// Declaramos el Iterador e imprimimos los Elementos del ArrayList
Iterator<String> nombreIterator = nombreArrayList.iterator();
while(nombreIterator.hasNext()){
	String elemento = nombreIterator.next();
	System.out.print(elemento+" / ");
}

When we run this code, we get the following on screen:


Elemento 1 / Elemento 2 / Elemento 3 / Elemento 3 / Elemento 4 / Elemento 5 / Elemento 6 / Elemento 7 / Elemento 8 / Elemento 9 / Elemento 10 /

As you can see in the result, "Elemento 3" appears twice, and we did that on purpose to show the next example. To keep working with ArrayLists, we’re now going to show the number of elements in the ArrayList, and then we’ll remove the first element of the ArrayList and the elements that are equal to "Elemento 3", which is why we put it in twice. We’ll remove "Elemento 3" with the iterator’s "remove()" method. Here is the code that does what we just described:


// Remember that we have already declared the ArrayList and the Iterator previously, like this:
// ArrayList<String> nombreArrayList = new ArrayList<String>();
// Iterator<String> nombreIterator = nombreArrayList.iterator();

// Get the number of elements in the ArrayList
int numElementos = nombreArrayList.size();
System.out.println("nnEl ArrayList tiene "+numElementos+" elementos");

// Remove the first element of the ArrayList, that is, the one at position '0'
System.out.println("n... Eliminamos el primer elemento del ArrayList ("+nombreArrayList.get(0)+")...");
nombreArrayList.remove(0);

// Remove the elements of the ArrayList that are equal to "Elemento 3"
System.out.println("n... Eliminamos los elementos de ArrayList que sean iguales a "Elemento 3" ...");
nombreIterator = nombreArrayList.iterator();
while(nombreIterator.hasNext()){
	String elemento = nombreIterator.next();
	if(elemento.equals("Elemento 3"))
		nombreIterator.remove();	// Remove the element we got from the Iterator
}

// Print the ArrayList after removing the elements equal to "Elemento 3"
System.out.println("nImprimimos los elementos del ArrayList tras realizar las eliminaciones: ");
nombreIterator = nombreArrayList.iterator();
while(nombreIterator.hasNext()){
	String elemento = nombreIterator.next();
	System.out.print(elemento+" / ");
}

// Show the number of elements in the ArrayList after the removals:
numElementos = nombreArrayList.size();
System.out.println("nNumero de elementos del ArrayList tras las eliminaciones = "+numElementos);

The output of this code is the following:


El ArrayList tiene 11 elementos

... Eliminamos el primer elemento del ArrayList (Elemento 1)...

... Eliminamos los elementos de ArrayList que sean iguales a "Elemento 3" ...

Imprimimos los elementos del ArrayList tras realizar las eliminaciones: 
Elemento 2 / Elemento 4 / Elemento 5 / Elemento 6 / Elemento 7 / Elemento 8 / Elemento 9 / Elemento 10 / 

Numero de elementos del ArrayList tras las eliminaciones = 8

If you look closely, we removed 3 elements from the ArrayList in two different ways: by asking for the position an element occupies in the ArrayList, and by asking for the content of an element in the ArrayList. As you can see, it’s very important to know how to use Iterators, since they let us handle the elements of the ArrayList.

All of this is very nice, but ArrayLists are generally used with objects rather than atomic data, since ArrayLists in Java are very powerful and easy-to-use structures.

Now let’s look at an example of using ArrayList with Objects. To do that, we’re going to create a class called "PartidoFutbol" (a football match), which we’ll use to create objects of that class that we’ll store in the ArrayList. First, here is the "PartidoFutbol" class:


package ArrayList_Objetos;

public class PartidoFutbol {

	private String equipoLocal;
	private String equipoVisitante;
	private int golesLocal;
	private int golesVisitante;

	public String getEquipoLocal() {
		return equipoLocal;
	}

	public void setEquipoLocal(String equipoLocal) {
		this.equipoLocal = equipoLocal;
	}

	public String getEquipoVisitante() {
		return equipoVisitante;
	}

	public void setEquipoVisitante(String equipoVisitante) {
		this.equipoVisitante = equipoVisitante;
	}

	public int getGolesLocal() {
		return golesLocal;
	}

	public void setGolesLocal(int golesLocal) {
		this.golesLocal = golesLocal;
	}

	public int getGolesVisitante() {
		return golesVisitante;
	}

	public void setGolesVisitante(int golesVisitante) {
		this.golesVisitante = golesVisitante;
	}
}

What we’re going to do in this example is read a series of football matches from a text file and store them in an ArrayList of "PartidoFutbol" objects. Since we’re using an ArrayList, we don’t care how many matches are in the text file, because ArrayLists, as we saw at the beginning, are dynamic. In this case I’ll tell you up front that there are 50 football matches in the file, but it wouldn’t matter how many there were.

Below is the code that reads the football matches and stores them in an ArrayList. Just out of curiosity, each football match is saved in the file with the following structure: equipoLocal::equipoVisitante::golesLocal::golesVisitante


// Create an ArrayList of objects of the "PartidoFutbol" class
System.out.println("... Nos creamos un ArrayList de objetos de la Clase "PartidoFutbol" ...");
ArrayList<PartidoFutbol> partidos = new ArrayList<PartidoFutbol>();

// Instantiate the file where the data is
File fichero = new File(nombreFichero);
Scanner s = null;

try {
	// Read the contents of the file
	System.out.println("... Leemos el contenido del fichero ...");
	s = new Scanner(fichero);
	// Get the football match data from the file
	while (s.hasNextLine()){
		String linea = s.nextLine();	// Get a line from the file (one football match)
		String [] cortarString = linea.split("::");		// Get the data of the football match
		PartidoFutbol partido = new PartidoFutbol();	// Create an object of the "PartidoFutbol" class

		// Set the attributes of the "partido" object
		partido.setEquipoLocal(cortarString[0]);
		partido.setEquipoVisitante(cortarString[1]);
		partido.setGolesLocal(Integer.parseInt(cortarString[2]));
		partido.setGolesVisitante(Integer.parseInt(cortarString[3]));

		// Add the "partido" object to the ArrayList
		partidos.add(partido);
	}

} catch (Exception e) {
	e.printStackTrace();
} finally{
	try {
		if (s != null)
			s.close();
	} catch (Exception e2) {
		e2.printStackTrace();
	}
}

System.out.println("... Guardados "+partidos.size()+" partidos de fútbol  ...");

With this code you can also see how to read a text file and process its data 😉 . Once this code has run, we have 50 football matches saved in the ArrayList "partidos". Now we traverse the ArrayList with an Iterator and print all the match results on screen. We do this just like before, with the Iterator:


System.out.println("n... Resultados de los partidos de Futbol ...");
Iterator<PartidoFutbol> itrPartidos = partidos.iterator();
while(itrPartidos.hasNext()){
	PartidoFutbol partido = itrPartidos.next();
	System.out.println(partido.getEquipoLocal() + " "
			+ partido.getGolesLocal() + "-"
			+ partido.getGolesVisitante() + " "
			+ partido.getEquipoVisitante());
}

The output of running this code is the following:


... Resultados de los partidos de Futbol ...
Valencia 1-0 Betis
Betis 1-0 Osasuna
Atletico Madrid 0-0 Zaragoza
Zaragoza 2-2 Valencia
Mallorca 0-1 Deportivo
Deportivo 1-0 Atletico Madrid
.
.
.
Mallorca 1-4 Malaga
Malaga 0-2 Atletico Madrid

Now we’re going to remove from the ArrayList all the matches that didn’t end in a draw. That way we’ll work with the iterator again. We do it like this:


// Remove the football matches from the ArrayList whose result
// is not a draw
System.out.println("n... Tamaño del ArrayList antes de eliminar partidos de futbol = "+partidos.size()+" ...");
System.out.println("n... Eliminamos los partidos de futbol cuyo resultado no sea un empate ...");
itrPartidos = partidos.iterator();
while(itrPartidos.hasNext()){
	PartidoFutbol partido = itrPartidos.next();
	// If the goals are not equal, remove the match
	if(partido.getGolesLocal() != partido.getGolesVisitante())
		itrPartidos.remove();
}

// Print the elements of the ArrayList
System.out.println("n... Tamaño del ArrayList despues de eliminar partidos de futbol = "+partidos.size()+" ...");
System.out.println("n... Resultados de los partidos de Futbol con empate ...");
itrPartidos = partidos.iterator();
while(itrPartidos.hasNext()){
	PartidoFutbol partido = itrPartidos.next();
	System.out.println(partido.getEquipoLocal() + " "
			+ partido.getGolesLocal() + "-"
			+ partido.getGolesVisitante() + " "
			+ partido.getEquipoVisitante());
}

As a result of running this code we get the following, and as you can see, the ArrayList has kept only the football matches that ended in a draw:


... Tamaño del ArrayList antes de eliminar partidos de futbol = 50 ...

... Eliminamos los partidos de futbol cuyo resultado no sea un empate ...

... Tamaño del ArrayList despues de eliminar partidos de futbol = 16 ...

... Resultados de los partidos de Futbol con empate ...
Atletico Madrid 0-0 Zaragoza
Zaragoza 2-2 Valencia
Alaves 0-0 Barcelona
Getafe 1-1 Athletic
Villarreal 1-1 Sevilla
Betis 0-0 Zaragoza
Valencia 2-2 Deportivo
Deportivo 1-1 Betis
Barcelona 2-2 Valencia
Getafe 1-1 Mallorca
Malaga 0-0 Alaves
Cadiz 1-1 Villarreal
Sevilla 0-0 Cadiz
Zaragoza 1-1 Deportivo
Barcelona 2-2 Zaragoza
Real Sociedad 1-1 Betis

With this we’ve seen how to use ArrayLists and the most important methods for doing so. That covers almost everything about ArrayLists in Java. Now all that’s left is to get comfortable and practice.

Finally, let’s go the extra mile and look at an example of how to work with an ArrayList of ArrayLists. This example may seem complex at first, but it really isn’t; it’s just a bit messy and you have to be careful. TRY TO DO THIS EXERCISE ON YOUR OWN BEFORE LOOKING AT THE SOLUTION, BECAUSE IF YOU MANAGE IT, NO ARRAYLIST TASK WILL BE ABLE TO RESIST YOU 😉

The exercise is the following. Given a file with a series of numbers, you have to remove all the zeros in the file, and if a line is full of zeros, you have to remove the line. In this case the file contains the following:


1 2 0 3 0 7 
0 0 0 0 
0 6 9 8 0 9 6 
0 0 0 0 7 9 0 0 
0 0 0 0 0 
8 7 0 8 9 0 8

And what we need to do is transform that data into the following:


1 2 3 7 
6 9 8 9 6 
7 9 
8 7 8 9 8

That is, all the zeros are removed, and since rows 2 and 5 contain only zeros, those rows have to be removed. To do this, we need to declare an ArrayList of ArrayLists of integers like this:


ArrayList<ArrayList<Integer>> arrayListNumeros = new ArrayList<ArrayList<Integer>>();

Next, we’ll read the numbers from the file and, for each row, create an ArrayList of integers in which we store each number in one position of the ArrayList, and then we store that ArrayList in the ArrayList we called "arrayListNumeros". We do it like this:


// Instantiate the file where the data is
File fichero = new File(nombreFichero);
Scanner s = null;

try {
	// Read the contents of the file
	System.out.println("... Leemos el contenido del fichero ...");
	s = new Scanner(fichero);
	// Get the football match data from the file
	while (s.hasNextLine()){
		String linea = s.nextLine();	// Get a line from the file with the numbers
		String [] cortarString = linea.split(" ");		// Get the numbers of the line into an array
		ArrayList<Integer> numeros = new ArrayList<Integer>();
		// Put the numbers of the row into the ArrayList
		for (int i=0; i<cortarString.length; i++){
			numeros.add(Integer.parseInt(cortarString[i]));
		}
		// Add the ArrayList of integers to the ArrayList of ArrayLists
		arrayListNumeros.add(numeros);	
	}

} catch (Exception e) {
	e.printStackTrace();
} finally{
	try {
		if (s != null)
			s.close();
	} catch (Exception e2) {
		e2.printStackTrace();
	}
}

To check that we copied the data correctly, and to see how to traverse an ArrayList of ArrayLists of Integers, we’ll print the contents of the ArrayList on screen like this:


// To check that we read the numbers from the file correctly, we traverse the ArrayList of
// ArrayLists and show it on screen.
System.out.println("n... Contenido de los ArrayList del ArrayList ...");
Iterator<ArrayList<Integer>> itrArrayListNumeros = arrayListNumeros.iterator();
while(itrArrayListNumeros.hasNext()){
	ArrayList<Integer> numeros = itrArrayListNumeros.next();
	Iterator<Integer> itrNumeros = numeros.iterator();
	while(itrNumeros.hasNext()){
		int numero = itrNumeros.next();
		System.out.print(numero+" ");
	}
	System.out.println();
}

The output is the contents of the file.
Now what we’re going to do is traverse the ArrayList of ArrayLists of Integers and remove from the ArrayLists all the elements whose content is '0'. We do it like this:


// Traverse the ArrayLists inside the ArrayList and remove the numbers that are zero
itrArrayListNumeros = arrayListNumeros.iterator();
while(itrArrayListNumeros.hasNext()){
	ArrayList<Integer> numeros = itrArrayListNumeros.next();
	Iterator<Integer> itrNumeros = numeros.iterator();
	while(itrNumeros.hasNext()){
		int numero = itrNumeros.next();
		if (numero == 0)
			itrNumeros.remove();
	}
}

Now we remove from the ArrayList the ArrayLists that are empty, checking with the "isEmpty()" method. We do it like this:


// Traverse the ArrayList of ArrayLists and remove the ArrayLists that don't
// contain elements
itrArrayListNumeros = arrayListNumeros.iterator();
while(itrArrayListNumeros.hasNext()){
	ArrayList<Integer> numeros = itrArrayListNumeros.next();
	// If the ArrayList is empty, remove it from the ArrayList
	if (numeros.isEmpty())
		itrArrayListNumeros.remove();
}

With all this we’ve removed the zeros and the ArrayLists that were empty. Now all that’s left is to traverse the ArrayList of ArrayLists again and show the contents after removing the zeros. We do it like this:


// Show the ArrayList after removing all the zeros
String salida = "";
System.out.println("n... Salida sin ceros ...");
itrArrayListNumeros = arrayListNumeros.iterator();
while(itrArrayListNumeros.hasNext()){
	ArrayList<Integer> numeros = itrArrayListNumeros.next();
	Iterator<Integer> itrNumeros = numeros.iterator();
	while(itrNumeros.hasNext()){
		int numero = itrNumeros.next();
		salida += numero+" ";
	}
	salida += "n";
}

System.out.println(salida);

After running this code, we see that we get the expected output, which is the following:


1 2 3 7 
6 9 8 9 6 
7 9 
8 7 8 9 8

With all this we’ve seen practically everything about ArrayLists, with examples of how to work with atomic elements (String, int, float, double, …) and with objects, and above all how to work with an ArrayList of ArrayLists, where, as you’ve seen, the complexity lies in knowing how to traverse that data structure.

You can download the code for all these examples (along with the corresponding files) from HERE.

If you have any questions, don’t hesitate to ask them by leaving a comment.

“ArrayList in Java, with Examples” by Ricardo Moya at jarroba.com, licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0. Registered at Safe Creative.

Ricardo Moya

I work in Machine Learning and Big Data. I like learning new technologies and explaining them as clearly as I can on this site.

You may also like

Sorting an ArrayList in Java

Learn how to sort an ArrayList in Java with Collections.sort and Comparator, for both simple values and objects, in ascending or descending order.

Nov 26, 2013

Map in Java, with Examples

Learn how to use the Java Map interface with examples: HashMap, TreeMap and LinkedHashMap, their key methods, iterators and working with your own objects.

Mar 1, 2014

Exceptions in Java, with Examples

Learn what exceptions are in Java, how the Throwable hierarchy works, and how to handle errors with try - catch - finally, with simple, practical examples.

Oct 12, 2014

Comments

Leave a comment


This site uses Akismet to reduce spam. Learn how your comment data is processed.