ArrayList in Java: a resizable array


Keywords: ArrayList, array, element

Learn programming Java Python

In this article, we will look at the class ArrayList, a standard class in Java that allows us to work with changing data collections. We will look closely at several different methods for working with an ArrayList and then use them to solve a longer example.

What is an ArrayList in Java?

First of all, the ArrayList class is a standard class in Java that enables you to work with changing data collections. This means that an ArrayList makes it easy to work with data that may change in quantity. The difference between a built-in array, as we saw on previous pages, and an ArrayList is that the size of an array cannot be changed. That is, if you want to add or remove elements in an array, you must create a new one, while elements to an ArrayList you can add and remove whenever you want.

Furthermore, we can illustrate an ArrayList in a similar way to an array and imagine that we have several storage locations that just continue on and on.

ArrayList Java Programming

Figure 1: ArrayList in Java

How to create ArrayList in Java?

Even though an ArrayList has great similarities to an array when it comes to the declaration, some things differentiate them. First, we can only save objects in an ArrayList and therefore need to specify the so-called wrapper class in the declaration; in other words, we can not save primitive data types in an ArrayList. The wrapper class is the type of data we want to save in our ArrayList. Further down below we will see a table with the primitive data type and their respective wrapper class

Syntax: Declare ArrayList in Java

Moreover, the syntax for declaring and working with an ArrayList compared to an array also deviates slightly.

 // imports the ArrayList class
import java.util.ArrayList;

// Declare ArrayList
ArrayList <WrapperClass> name = new ArrayList <WrapperClass>(); 

Let’s take it step by step

Primitive data types and corresponding Wrapper class

As we mentioned above, we can only save objects in an ArrayList and therefore need to specify the wrapper class.

Primitive data typeWrapper class
byteByte
charCharacter
intInteger
doubleDouble
booleanBoolean
floatFloat

How to use an ArrayList in Java?

As we have now described, there are great similarities between an ArrayList and an array in Java. Apart from the big difference that an ArrayList is a variable list of data, there are differences in the commands we use when working with an ArrayList compared to an array. In other words, the commands we can execute are basically the same, but the way we declare these commands and invoke different methods differs

Let’s go through some useful features for working with an ArrayList. We start by creating a list of integers that we call listEx that we will use.

// imports the ArrayList class
import java.util.ArrayList;

public class Example{
   public static void main(String[] args) { 

   // Declare ArrayList named listEx 
   ArrayList <Integer> listEx = new ArrayList <Integer> (); 
   }
}

Add elements to an ArrayList

To add an element to our ArrayList we use the built-in add() method.

// Add elements to an ArrayList
listEx.add(12);
listEx.add(5);
listEx.add(23);
listEx.add(8);

The method adds the element to the first free place in the list. In other words, we will get:

ArrayList Example Java

Figure 2: Example of ArrayList

Add elements to specific index in ArrayList

However, if we want to add an element to a specific place in the list, i.e. a given index, we use the add() method again and write the index, a colon, and then the value we want to add in the parentheses.

// Add elements to an ArrayList on specific index
listEx.add(3,62);
listEx.add(1,999);

What the method does is enter the element on the index we specified and then move all other elements one step to the right. In the example we are working with, this will result in

Example Add ArrayList

Figure 3: Use add () to add elements to specific index

Important: we cannot add elements outside the length of the list. This means that we cannot have a space between the elements initiated in the list. For example, we have elements on index 0 – 5 and then on index 8 is not possible.

If we were to try to add an element to, for example, index 8 in our list, listEx in the figure above, we would get an error message that says:

java.lang.IndexOutOfBoundsException: Index: 8, Size: 6

Use element in ArrayList

Okay, but now we’ve saved a couple of values in our ArrayList called listEx, and now we want to start using them. To read an element in ArrayList, the get() method is used, and we enter the index number of the element we want to read. For example,

// Retrieves the value
int number = listEx.get(4); 

The variable number will be equal to 62.

Change element in ArrayList

However, if we want to change an element in the list, we use the set() method and enter the index number for the place we want to change, a colon, and then the value we want to replace it with.

// Change the value
listEx.set(4, 45);

// Retrieve the value again 
int number = listEx.get(4);

Then the value of number will instead be 45.

Remove element from ArrayList

Furthermore, if we want to remove an element from our list, we use the remove() method and specify which index in the list we want to remove. For example, if we want to remove the element, we added to index 1 in the list.

// Removes the element on index 1
listEx.remove(1);

Then the element on the index will be removed, and all elements that appear later in the list, i.e. to the right in our figure, will be moved one step to the left. If we update our figure for listEx, we get:

Remove element ArrayList Java

Figure 4: Example of the remove () method for ArrayList

Length of ArrayList

If we want to know how long an ArrayList is, in other words, the number of elements, we write the name of the ArrayList we are working with, followed by .size(). The size() method specifies the number of elements in the list and not the inserted value.

For example,

// The number of elements in listEx
listEx.size(); 

System.out.println("Length of the ArrayList listEx: " + listEx.size());

We get the result

Length of the ArrayList listEx: 5

Pay attention to the fact that, similar to an array, the length of an ArrayList will be one greater than the index. This is simply because the index always starts at 0, and the length is calculated as the number of elements.

Iterate ArrayList

If we want to loop through a list from start to finish, we do it in the same way as for an array, where we advantageously use a for-loop. For example, we now want to sum all the values we have saved in listEx.

int total = 0;  

// For-loop to iterate the list
for (int i = 0; i < listEx.size(); i++) {

   // Add up the sum
   total = total + listEx.get(i);      
}
// Print the result
System.out.println("The sum of the elements in the list: " + total);  

Resulting in

Summan av elementen i listan är: 110

Note, that in the for loop, we use the size() method instead of the length method we used when working with an array.

Find index for specific value in ArrayList

Using the built-in method indexOf(), we can search through an ArrayList and return the index where the given value is located. The method returns the index of the first occurrence of the element we are looking for, and if the element is not found in the list, -1 is returned.

For example, if we use indexOf () on the ArrayList listEx that we work with

import java.util.ArrayList;

public class Example{
   public static void main(String[] args) { 

   ArrayList <Integer> listEx = new ArrayList <Integer> (); 
   // Add elements to listEx
   listEx.add(12);
   listEx.add(5);
   listEx.add(23);
   listEx.add(8);

   // Search for the value 8
   int indSearchOne = listEx.indexOf(8);

   // Search for the value 95
   int indSearchTwo = listEx.indexOf(95); 

   System.out.println(indSearchOne);
   System.out.println(indSearchTwo);
   }
}

We will get the result

4 
-1

Sort an ArrayList

Another useful class in the java.util package is the Collections class, which includes the sort() method that we can use to sort lists alphabetically or numerically.

// Import collections class
import java.util.Collections; 
 
// Sort the items in the list
Collections.sort(listEx);

If we update our figure for listEx:

sort() method ArrayList Java

Figure 5: Example of the sort () method for ArrayList

Remove all elements in ArrayList

To remove all elements in an ArrayList, the clear() method is used.

// Clear all elements in the ArrayList named listEx
listEx.clear(); 

Summary: methods for ArrayList

The table below is a summary of some of the most useful methods for ArrayList in Java.

MethodDescription
add() Adds elements to the list
addAll()Adds all elements in a list to another list
clear()Removes all elements from the list
contains()Returns true if the list contains the specified element
get()Returns the element at the specified position in the list
indexOf()Returns the index of the first occurrence of the specified element in the list, or -1 if the list does not contain the element
isEmpty()Returns true if the list does not contain any elements
lastIndexOf()Returns the index of the last occurrence of the specified element in the list, or -1 if the list does not contain the element.
remove()Deletes the item at the specified position in the list
set()Replaces the element at the specified position in the list with the specified element
size()Returns the number of elements in the list
sort()Sorts the list in alphabetical or numeric order
toArray()Converts a list to an array that contains all the elements from the list

For a complete list of all methods, see the documentation for the ArrayList class at Oracle

Example: ArrayList in Java

We have now gone through a number of different methods that we can use when working with an ArrayList. But let’s now try to use several of them to solve an example.

What we are going to do is write a program where the user should be able to specify participants for a list. The program should give the user a couple of choices, such as a simpler menu, and based on which number is entered; the following functions should be performed.

  • 1: Add a participant name to the list.
  • 2: Remove a participant using indexes from the list.
  • 3: Find the participant number (index) of a participant.
  • 4: Print a list of all participants in the list and their respective participant numbers.
  • 5: Sort the list in alphabetical order.
  • 9: Exit the program.

If the user enters an incorrect input to the menu, we will print it, and the user may try again. The first thing we do is to import the class Scanner, ArrayList and Collections.

// Imports the Scanner class
import java.util.Scanner;

// Imports the ArrayList class
import java.util.ArrayList;

// Imports the Collections class
import java.util.Collections;

Furthermore, we then create our ArrayList and Scanner objects to be able to take in information from the user and be able to save the information.

public class ExampleArrayList{
   public static void main(String[] args) {

      // Save the participant names in a list
      ArrayList <String> userNames = new ArrayList <String> ();

      // Input from the user
      Scanner in = new Scanner(System.in);

      boolean runProg = true;

Moreover, the next thing we do is to set up the while loop and else-if statements we will use.

while (runProg){

    System.out.println("Enter 1 to add a participant" +
        "\nEnter 2 to remove a participant" +
        "\nEnter 3 to find the participant number of a participant" +
        "\nEnter 4 to print a list of all participants" +
        "\nEnter 5 to sort the list in alphabetical order" +
        "\nEnter 9 to end the program" );

    int input = in.nextInt();

    if (input == 1){
        System.out.println("Enter the name of the participant: ");
            userNames.add(in.next());
    }

    else if (input == 2){
        System.out.println("Enter participant number for participant: ");
            userNames.remove(in.nextInt());
    }

    else if (input == 3){
        System.out.println("Enter the name of the participant: ");

        String findName = in.next();
        
        if (userNames.indexOf(findName) != -1){
            System.out.println("Participant: " + findName +
                " is on the index: " + userNames.indexOf(findName)+ "\n");
            }
        else{
            System.out.println("Participant: " + findName +
                " not found in the list");
        }
    }

    else if (input == 4){
        for (int i = 0; i < userNames.size(); i++){
            System.out.println("Number: " + i +
                 "\t Name: " + userNames.get(i));
        }
        System.out.println();
    }
    else if(input == 5){
        Collections.sort(userNames);
        System.out.println("The list is sorted in alphabetical order\n");
    }

    else if (input == 9){
        System.out.println("The program ends");
        runProg = false;
    }

    else {
        System.out.println("Incorrect input. Try again\n");
    }
}
}
}

Finally, if you would like to test the entire code in the example above, you can do so by using the button below.

Try example online

Summary: ArrayList in Java

If we are to briefly summarize an ArrayList in Java in three points, it is:

  • A standard class that enables you to work with changing data collections.
  • Only possible to save objects in an ArrayList. Therefore, we need to specify the wrapper class in the declaration; that is, we can not save primitive data types in an ArrayList.
  • To work with a list in Java, there are several built-in methods in the class ArrayList. A summary of the most useful methods can be found higher up on this page or in the documentation for the ArrayList class at Oracle

FAQ: ArrayList in Java

How to add and use an element in ArrayList?

To add an element to an ArrayList, use the add () method. Furthermore, to use an element that is saved in the list, the get () method is used.

How to find the length of ArrayList in Java?

If we want to know how long an ArrayList is, we write the name of the ArrayList we are working with, followed by .size (). The size () function specifies the number of items in the list, and not the inserted values.

How to remove an element in an ArrayList?

If you want to remove an element from your list, use the remove () method and specify which index in the list you want to remove. Alternatively, to remove all elements in an ArrayList, you can use the clear () method.