How the ArrayList works in Java, with examples.

How the ArrayList works in Java, with examples.

In programming, you will always work with many values. You can choose to store one value at ago into a variable, for example, int num1 = 2; int num2 = 4; int num3 = 6; etc, but what if you have thousands of values to store? The approach above would be impractical. we need a way to dynamically add, remove, replace our values and work with our values.

Java provides us with ArrayList a tool used to store large amounts of data of the same type. It helps us to work with the list. The ArrayList comes with various methods for adding a value to the list, removing a value from the list, and also for getting a specific value in a specific position in the list. We don't have to worry about the inner workings of the ArrayList at the moment, but rather make good use of it.

In this article, we are going to learn how to use a list in Java. We are going to learn how to add values to the list, how to retrieve information from the list, how to iterate over a list using a while loop, a for loop and for-each loop, how to check if a value exists in a list and how to remove a value from a list. We have quite a lot to cover, so let's dive right in.

If you want to use ArrayList in your program, the first thing you have to do is import it. You import it by adding a command import java.util.ArrayList at the top of the program as shown below

import java.util.ArrayList; 
public class Main {
    public static void main(String[] args) {
       // we are yet to use ArrayList
  }
}

To create a new ArrayList, you use the command ArrayList<Type> songs = new ArrayList<>(); . As we mentioned above, The ArrayList stores values of the same type. So the Type stands for the type of values to be stored for example Integers, Strings, Booleans etc. Let's now create a list to store our favorite songs.

import java.util.ArrayList; 
public class Main {
    public static void main(String[] args) {
       //create list to store our favorite songs
      ArrayList<String> songs = new ArrayList<>();
  }
}

Let's briefly talk about variables. In Java, to work with a certain value, we store it in a variable. To create a variable, we need to give it a type, a name and a value

type variableName = value;
int age = 10;

Think of ArrayList<String> songs as a variable, it should have a name and a type. The name for the variable of type ArrayList is songs . When the ArrayList variable is initialized, the type of values to be stored is defined in addition to the variable type.

An ArrayList variable is a Reference type variable. Reference-type variables contain a reference to the spot that holds the values relating to that variable. These can store almost a limitless number of values, unlike primitive type variables that store a very limited number of values.

When you create an ArrayList, it assumes that all the variables contained in it are reference variables. In Java, a primitive int variable is automatically converted to a variable of reference type Integer , the same thing happens to primitives string, double, boolean which are converted to the references String, Double, Boolean respectively.

Adding a value to a list is done using a list method add , the method takes the value to be added as a parameter. Let's see an example of how to add to a list.


import java.util.ArrayList;

public class Main {

  public static void main(String[] args) {
    ArrayList<String> hymns = new ArrayList<>();
    hymns.add("In Christ Alone");
    hymns.add("My Jesus I Love Thee");
    hymns.add("He Leadeth Me");

    System.out.println(hymns.get(0));
  }

}

A new list hymns was created and favorite hymns were to the list using the add method. To call a list method, write the name of the variable describing the list followed by the dot and the name of the method.

We can retrieve a value at a certain position in a list using the get method. The method is given an integer as a parameter that represents the position of the value in a list. It should be noted that positions in a list are counted beginning from 0. Let's use our hymns list to get the first and third songs and then print them to the console

import java.util.ArrayList;

public class Main {

  public static void main(String[] args) {
    ArrayList<String> hymns = new ArrayList<>();
    hymns.add("In Christ Alone");
    hymns.add("My Jesus I Love Thee");
    hymns.add("He Leadeth Me");

    System.out.println(hymns.get(0));
    System.out.println(hymns.get(2));
  }

}

The code snippet above prints the following result.

In Christ Alone
He Leadeth Me

You may ask, what happens when you try to retrieve a value from a place that does not exist in a list? Good one! When you try to retrieve information from a place that does not exist in a list, your program will throw IndexOutOfBoundsException error. Most Java programmers call the error Exception . To illustrate how IndexOutOfBoundsException error, let's try to retrieve a song from the third position in the hymns list.

import java.util.ArrayList;

public class Main {

  public static void main(String[] args) {
    ArrayList<String> hymns = new ArrayList<>();
    hymns.add("In Christ Alone");
    hymns.add("My Jesus I Love Thee");
    hymns.add("He Leadeth Me");

    System.out.println(hymns.get(3));
  }

}

Running the program above will print the result below

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3

To iterate in programming means to repeat a process in a computer program until a condition is met. In this part of this article, we are going to learn how to iterate over a list using a while loop , and a for loop . Later on, we will learn how to iterate over a list using a for-each loop .

Let's start with an example where we print all items in a list one by one;

import java.util.ArrayList;

public class Main {

  public static void main(String[] args) {
    ArrayList<String> students = new ArrayList<>();
    students.add("Innocent");
    students.add("Viola");
    students.add("Sarah");
    students.add("Richard");

    System.out.println(students.get(0));
    System.out.println(students.get(1));
    System.out.println(students.get(2));
    System.out.println(students.get(3));
  }

}

Running the program above will print the following to the console

Innocent
Viola
Sarah
Richard

Although the program in the example above works, it is impractical. For instance, what happens if we have about a thousand values in a list, and what about if we don't know the number of values in a list?

We can get the number of values in a list using the list size method. The method will return an integer that can be used as part of the expression or stored in a variable to use later.

Let's see how can use a while loop to iterate over a list of students.

import java.util.ArrayList;

public class Main {

  public static void main(String[] args) {
    ArrayList<String> students = new ArrayList<>();
    students.add("Innocent");
    students.add("Viola");
    students.add("Sarah");
    students.add("Richard");

    int index = 0;

    while(index < students.size()){
      System.out.println(students.get(index));
      index = index + 1;
    }
  }

}

The program above prints the following output to the console.

Innocent
Viola
Sarah
Richard

We create a variable index to track the position of a certain value in a list, then iterate through the list using a while loop until the condition index < students.size() no longer apply. In simple terms, we repeat the process of printing the value at a position in a list as long as the value of the index is less than the size of the number of values in a list.

The next example shows how to iterate through a list of integers using a while loop.

import java.util.ArrayList;

public class Main {

  public static void main(String[] args) {
    // create a list of ages
    ArrayList<Integer> ages = new ArrayList<>();
    ages.add(17);
    ages.add(21);
    ages.add(24);
    ages.add(27);

    int index = 0;
    // using a while loop to iterate over ages
    while(index < ages.size()){
      System.out.print(ages.get(index) + ", ");
      index = index + 1;
    }
  }

}

Running the program above will print the following results to the console

17, 21, 24, 27,

We can also use the for loop to iterate over a list. To create a for loop, we start by writing the keyword for followed by the opening parenthesis; we then define the initialization statement, the condition to be met and the update clause all separated by a semicolon and we close the parenthesis; Everything we want to do during the for loop is put between the opening and closing curly brackets.

for(int i = 0; i < list.size(); i++){
    // do something here
}

In the next example, a list of cities is created and then a for loop is used to iterate over each city and print it to the console until all cities have been printed.

import java.util.ArrayList;

public class Main {

  public static void main(String[] args) {
    // create a list of cities
    ArrayList<String> cities = new ArrayList<>();
    cities.add("London");
    cities.add("Paris");
    cities.add("Tokyo");
    cities.add("Rome");
    // using a for loop to iterate over cities
    for(int i = 0; i < cities.size(); i++) {
      System.out.print(cities.get(i) + " ");
    }
  }

}

Running the program above will print the results below;

London Paris Tokyo Rome

The enhanced for loop , which is sometimes referred to as for-each loop is simple, readable and allows us to visit every element in a list. You don't even need to keep track of the index if you are to use it.

The syntax for an enhanced loop is as follows

for(dataType item : listToIterate) {
    ...
}

Let's use an enhanced loop to iterate over the list of cities in the previous example.

import java.util.ArrayList;

public class Main {

  public static void main(String[] args) {
    ArrayList<String> cities = new ArrayList<>();
    cities.add("London");
    cities.add("Paris");
    cities.add("Tokyo");
    cities.add("Rome");
    // using an enhanced for loop to iterate over cities
    for(String city: cities) {
      System.out.print(city + " ");
    }
  }

}

To remove a value from a list, we utilize ArrayList's remove method. The method removes the value found at the index passed to it as a parameter. The remove method always receives an integer as a parameter.

import java.util.ArrayList;

public class Main {

  public static void main(String[] args) {
    // list of programming languages
    ArrayList<String> languages = new ArrayList<>();
    languages.add("JavaScript");
    languages.add("Java");
    languages.add("PHP");
    languages.add("C");

    // we can remove PHP from our list, sorry PHP programmers
    languages.remove(2);
    // printing the rest of the languages
    for(String language: languages) {
        System.out.println(language);
    }
  }

}

For lists containing integer values, we remove the value from the list by converting it to Integer type with the help of the valueOf method of the integer class.

When you directly pass an integer as a parameter to remove the integer value from a list, it will remove the number from that position the parameter indicates. Let's illustrate this using an example.

import java.util.ArrayList;

public class Main {

  public static void main(String[] args) {
    ArrayList<Integer> numbers = new ArrayList<>();
    numbers.add(20);
    numbers.add(22);
    numbers.add(26);
    numbers.add(24);

    // removes the number at position 2.
    numbers.remove(2);

    // removes number 20 from the list
    numbers.remove(Integer.valueOf(20));
    for(Integer number: numbers) {
        System.out.println(number);
    }
  }

}

To check if a value exists in a list, we use the ArrayList contains method. The method receives the value we are looking for as a parameter and it will return a boolean type value(true or false) indicating whether or not the value we are looking for exists in a list.

In the previous example, we removed PHP from the list of languages . Let's confirm if it is still on the list using the contains method.

import java.util.ArrayList;

public class Main {

  public static void main(String[] args) {
    ArrayList<String> languages = new ArrayList<>();
    languages.add("JavaScript");
    languages.add("Java");
    languages.add("PHP");
    languages.add("C");

    languages.remove(2);

    boolean found = languages.contains("PHP");

    if (found) {
      System.out.println("It exists!");
    } else {
      System.out.println("It is not found");
    }

  }

}

Running the program above will print the following to the console.

It is not found

The ArrayList is a very useful feature in Java. In this article, we have learned list methods for adding to the list, removing from the list, and checking if a value exists on a list or not. We've also seen how to iterate over lists using different iteration methods. You can learn more about ArrayLists from the official documentation.