Java ArrayList for Absolute Beginners with Examples

By Eric Murithi August 1, 2019 - 12:39 Java ArrayList for Absolute Beginners with Examples Caption: ArrayList in Java

ArrayLists will be helpful when creating large Java programs. In this article, I am going to teach you what a Java ArrayList is, how to use it, and what operations you can apply to it.

What is an ArrayList?

In Java, ArrayList is simply used to store dynamically sized collections of items. ArrayList stores items of the same data type. Remember that everything in Java is an object and when creating an ArrayList, you’re creating a Java object of type ArrayList.

Hence, creating an ArrayList is not different from creating other objects such as int, double, or String. However, what's unique about ArrayList is that it an object that contains other objects, such as Integer, String, Person (You own object) or even ArrayList itself.

Contrary to standard Arrays that have a fixed size, an ArrayList automatically grows its size or shrinks when items are added to it or removed from it respectively. Thus, when declaring an ArrayList, you will not specify its length, unlike in Arrays.

Similar to Arrays, ArrayList stores ordered items. This means that each item in the ArrayList has an index that uniquely identifies this item. This means that items are not randomly added to the ArrayList and scattered around.

For example, consider this ArrayList; {“hello”, “everyone”, “on”, “board”}. “hello” would be the first item in our ArrayList identified with index 0. “everyone” the second item identified with index 1 and so on. Remember in Java programming language, indexes start from 0 and NOT 1.

The ArrayList class extends AbstractList and implements the List interface. The figure below illustrates the Java ArrayList class hierarchy.


The above diagram represents the following:

  1. ArrayList is a class, and it extends List interface.
  2. List is an interface, and it extends Collection interface.
  3. Collection is an interface, and it extends Iterable interface.
  4. Iterable is an interface.

Key points to remember about Java ArrayList:

  1. It's also called a dynamic array since it is re-sizable. When new items are added, the length grows, and when items are removed, the length shrinks.
  2. It is an ordered collection of items. It is not a bag that you randomly add items and scatter around. It maintains the order of the items and uniquely identifies items using an index. 
  3. It allows you to retrieve items by their index because internally, it uses an array to store items.
  4. You cannot create an ArrayList of primitive data types like int, char, float, double, boolean, etc. You need to use boxed types like Integer, Character, Float, Double, Boolean, etc. 
  5. ArrayList in Java allows duplicate and null values.
  6. ArrayList in Java is not synchronized. This means that if multiple threads try to modify the ArrayList at the same time, the outcome will be non-deterministic. Therefore, you must explicitly synchronize access to an ArrayList if multiple threads are going to modify it.

Now with that elaboration, let’s do some coding. But before we can do anything with ArrayLists. We need to know how a Java ArrayList is created.

How to create a Java ArrayList?

Creating ArrayList in Java is very simple.

You can create an empty ArrayList fruits like this

ArrayList <String> fruits = new ArrayList<>();

Note that you must import java.util.ArrayList.

Similar to creating variables of other types, Java first allocates some memory for the ArrayList object and assigns the variable fruits to refer to it.

ArrayList in Java is created by declaring the data type of items inside <> e.g., String and then the variable name of the ArrayList e.g., fruits. Then you have to initialize your ArrayList with new ArrayList<>() to avoid NullPointerException.

1. Creating an ArrayList and adding items to it

Now let us create an ArrayList and add items to it. You add items by using the add() function.

import java.util.ArrayList;
class SimpleArrayListExample {
    public static void main(String[] args) {
        // Creating an ArrayList of String
        ArrayList<String> fruits = new ArrayList<>();
        // Adding new items to the ArrayList
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");
        fruits.add("Pawpaw");
        fruits.add("Dates");
        //Print list of fruits
        System.out.println(fruits);
    }
}

The following is the output of our code.

run:
[Apple, Banana, Orange, Pawpaw, Dates]

2. Creating an ArrayList from another collection

You can create an ArrayList from another collection by specifying the collection inside the () brackets. If not the collection is provided inside the brackets, the ArrayList will be empty.

Now let’s create an ArrayList from another collection. You can do that by creating the first ArrayList and add items to it and then create a second Arraylist from the first ArrayList or adding the entire first ArrayList to the second ArrayList.

i. Creating an ArrayList from another collection

import java.util.ArrayList;
class SimpleArrayListExample {
    public static void main(String[] args) {
        // Creating an ArrayList of String
        ArrayList<String> fiveFruits = new ArrayList<>();
        // Adding new items to the ArrayList
        fiveFruits.add("Apple");
        fiveFruits.add("Banana");
        fiveFruits.add("Orange");
        fiveFruits.add("Pawpaw");
        fiveFruits.add("Dates");
        // Creating an ArrayList from another collection
        ArrayList<String> fruits = new ArrayList<>(fiveFruits);
        fruits.add("Cucumbers");
        fruits.add("Peach");
        fruits.add("Grapes");
        fruits.add("Guava");
        fruits.add("Kiwi");
        
        //Print list of fruits
        System.out.println(fruits);
    }
}

The following is the output of our code.

run:
[Apple, Banana, Orange, Pawpaw, Dates, Cucumbers, Peach, Grapes, Guava, Kiwi]

ii. Adding an entire collection to an ArrayList

import java.util.ArrayList;
class SimpleArrayListExample {
    public static void main(String[] args) {
        // Creating an ArrayList of String
        ArrayList<String> fiveFruits = new ArrayList<>();
        // Adding new items to the ArrayList
        fiveFruits.add("Apple");
        fiveFruits.add("Banana");
        fiveFruits.add("Orange");
        fiveFruits.add("Pawpaw");
        fiveFruits.add("Dates");
        // Adding an entire collection to an ArrayList
        ArrayList<String> fruits = new ArrayList<>();
        fruits.addAll(fiveFruits);
        fruits.add("Cucumbers");
        fruits.add("Peach");
        fruits.add("Grapes");
        fruits.add("Guava");
        fruits.add("Kiwi");
        
        //Print list of fruits
        System.out.println(fruits);
    }
}

The following is the output of our code.

run:
[Apple, Banana, Orange, Pawpaw, Dates, Cucumbers, Peach, Grapes, Guava, Kiwi]

That's interesting. We can create an ArrayList and print out the items in it. And the items in the ArrayList are the same type. Can store items of different types in an ArrayList or do they have to be of the same type?

What type of items can I store in a Java ArrayList?

Java is a strongly typed language.

ArrayList essentially store related objects, and because of that, then you cannot store anything in the ArrayList. All items in the ArrayList must be of the same data type.

When we declare an ArrayList, we also define the type of items to be stored. The type is declared inside <> sign. In our examples above, we created ArrayList to contain items of data type String. And when we try to add int items in the ArrayList, we get an error.

There is a limitation that an ArrayList can store only items of the same data type. Nevertheless, you can define any type of values to be stored when declaring the ArrayList. Take a look at this example.

import java.util.ArrayList;
class SimpleArrayListExample {
    public static void main(String[] args) {
        // Creating an ArrayList of String
        ArrayList<String> fruits = new ArrayList<>();
        //Adding items to ArrayList of String
        fruits.add("Cucumbers");
        fruits.add("Peach");
        fruits.add("Grapes");
        fruits.add("Guava");
        fruits.add("Kiwi");
        
        // Creating an ArrayList of Integer
        ArrayList<Integer> primeNumbers = new ArrayList<>();
        
        //Adding items to ArrayList of String
        primeNumbers.add(3);
        primeNumbers.add(5);
        primeNumbers.add(7);
        primeNumbers.add(11);
        primeNumbers.add(13);
    }
}

Here we have many ArrayLists, and each holds items of the same data type.

Thus, even though ArrayList are flexible regarding their size, they are not flexible regarding the data type of items they can store. This is due to the fact that Java is a strongly typed language. See my article, comparison of Java with other languages.

Accessing items from an ArrayList

Earlier I mentioned that an ArrayList is an ordered collection of items and also each item in the ArrayList has an index that uniquely identifies them.

That said, you can easily access a particular item in the ArrayList given its index. So if you know the index of the item you want to access, then accessing that item is very straightforward. Just use the get() method and put the index of the item inside the brackets.

Let’s try that in an example.

import java.util.ArrayList;
class SimpleArrayListExample {
    public static void main(String[] args) {
        // Creating an ArrayList of String
        ArrayList<String> fruits = new ArrayList<>();
        //Adding items to ArrayList of String
        fruits.add("Cucumbers");
        fruits.add("Peach");
        fruits.add("Grapes");
        fruits.add("Guava");
        fruits.add("Kiwi");
        
        //Accessing item at index 0
        String fruit = fruits.get(0);
        
        //Print out the item accessed
        System.out.println(fruit);
    }
}

The following is the output of the code.

run:
Cucumbers

There are some instances where you don’t know the index of the item. And when you try to access the item, you may get an error ArrayIndexOutOfBounds. This is because the ArrayList is empty or you are trying to access an index that is not there.

Example

import java.util.ArrayList;
class SimpleArrayListExample {
    public static void main(String[] args) {
        // Creating an ArrayList of String
        ArrayList<String> fruits = new ArrayList<>();
        //Adding items to ArrayList of String
        fruits.add("Cucumbers");
        fruits.add("Peach");
        fruits.add("Grapes");
        fruits.add("Guava");
        fruits.add("Kiwi");
        
        //Accessing item at index 10
        String fruit = fruits.get(10);
        
        //Print out the item accessed
        System.out.println(fruit);
    }
}

Output

run:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 10, Size: 5
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at ArrayLists.SimpleArrayListExample.main(SimpleExample.java:13)
C:\Users\eric\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1

Therefore the safest way is to check if the ArrayList is empty or not. And also checking the size of the array.

We use the isEmpty() method to check if the ArrayList is empty and use size() method to find the size of the ArrayList.

Example when ArrayList is empty

import java.util.ArrayList;
class SimpleArrayListExample {
    public static void main(String[] args) {
        // Creating an ArrayList of String
        ArrayList<String> fruits = new ArrayList<>();
        //Accessing item at index 0
        if (fruits.isEmpty()) {
            System.out.println("The ArrayList is Empty");
        } else {
            String fruit = fruits.get(0);
            //Print out the item accessed
            System.out.println(fruit);
        }
    }
}

Output

run:
The ArrayList is Empty

Therefore when you find out that the ArrayList is empty do not try reading the index. Similarly, when you find that the size of an ArrayList is less than index you want to read, do not read the ArrayList index.

Example when index if bigger than number of items

import java.util.ArrayList;
class SimpleArrayListExample {
    public static void main(String[] args) {
        // Creating an ArrayList of String
        ArrayList<String> fruits = new ArrayList<>();
        //Adding items to ArrayList
        fruits.add("Cucumbers");
        fruits.add("Peach");
        fruits.add("Grapes");
        fruits.add("Guava");
        fruits.add("Kiwi");
        
        int index = 6;
        //Accessing item at index 6
        if (fruits.size() < index ) {
            System.out.println("The ArrayList does not have index "+index);
        } else {
            String fruit = fruits.get(index);
            //Print out the item accessed
            System.out.println(fruit);
        }
    }
}

Output

run:
The ArrayList does not have index 6

Iterating over the items in an ArrayList

At some point in your program, you’ll need to iterate over all the items of an ArrayList. Let’s say we need to print all the items in an ArrayList. One way to do that is to iterate over all the items in the ArrayList, one by one, and print the item.

You can use for loop to do that. Let’s see an example.

import java.util.ArrayList;
class SimpleArrayListExample {
    public static void main(String[] args) {
        // Creating an ArrayList of String
        ArrayList<String> fruits = new ArrayList<>();
        //Adding items to ArrayList
        fruits.add("Cucumbers");
        fruits.add("Peach");
        fruits.add("Grapes");
        fruits.add("Guava");
        fruits.add("Kiwi");
        
        //Use for loop to iterate over items
        for(String fruit : fruits){
            System.out.println(fruit);
        }
    }
}

The following is the output.

run:
Cucumbers
Peach
Grapes
Guava
Kiwi

When you use a for loop to iterate over an ArrayList, in each iteration, fruit will store the value of one of the items in the list, one at a time, ordered by their index — this kind of for loop iterates over all the items in the ArrayList. 

You can also iterate over an ArrayList with for loop to check if an item exists in an ArrayList or not. For example, to know if "Grapes" is contained in an ArrayList, we can iterate over the items one by one and check if the item is actually "Grapes."

Example

import java.util.ArrayList;
class SimpleArrayListExample {
    public static void main(String[] args) {
        // Creating an ArrayList of String
        ArrayList<String> fruits = new ArrayList<>();
        //Adding items to ArrayList
        fruits.add("Cucumbers");
        fruits.add("Peach");
        fruits.add("Grapes");
        fruits.add("Guava");
        fruits.add("Kiwi");
        fruits.add("Grapes");
        
        //Use for loop to iterate over items and check if apple
        for(int index = 0; index < fruits.size(); index++){
            if(fruits.get(index).equals("Grapes")){
                System.out.println("Grapes found at index "+index);
            }
        }
    }
}

Output

run:
Grapes found at index 2
Grapes found at index 5

Java provides an easier way to check if an item exists in an ArrayList.

How to check if an item exists in an ArrayList? (contains() method)

You will need to check if an item exists in an ArrayList. The ArrayList class provides a useful method that allows us to quickly check if an item is a member of an ArrayList or not. This method if called contains().

This method works in all Java sequence types (String, arrays, and lists). It expects one parameter, which is the item to test. It returns true if the item is in the ArrayList and false otherwise. 

Let’s see the example below.

import java.util.ArrayList;
class SimpleArrayListExample {
    public static void main(String[] args) {
        // Creating an ArrayList of String
        ArrayList<String> fruits = new ArrayList<>();
        //Adding items to ArrayList
        fruits.add("Cucumbers");
        fruits.add("Peach");
        fruits.add("Grapes");
        fruits.add("Guava");
        fruits.add("Kiwi");
        fruits.add("Grapes");
        
        //Use contains() method to check is Apple exists in the ArrayList
        if(fruits.contains("Apple")){
            System.out.println("The ArrayList contains Apple");
        }else{
            System.out.println("The ArrayList does not contains Apple");
        }
    }
}

The following is the output of the code.

run:
The ArrayList does not contains Apple

So far we are able to create an ArrayList, add items in an ArrayList, read an item in an ArrayList, iterate over all the items in an ArrayList and check if an item exists in an ArrayList. The next thing we need to know in Java ArrayList is how to modify an item in an ArrayList.

How to change an item in an ArrayList?

Java ArrayList is mutable. This means that we can modify or change the contents of an ArrayList. You can learn more about mutable and immutable objects in Java. The article explains very well about them.

It very simple to modify the item at a particular index. We usually use the set() method. Here we provide two parameters, first the index of the item and then the new value. Kindly remember to check if the index exists before trying to change.

Let’s see the example below.

import java.util.ArrayList;
class SimpleArrayListExample {
    public static void main(String[] args) {
        // Creating an ArrayList of String
        ArrayList<String> fruits = new ArrayList<>();
        //Adding items to ArrayList
        fruits.add("Cucumbers");
        fruits.add("Peach");
        fruits.add("Grapes");
        fruits.add("Guava");
        fruits.add("Kiwi");
        fruits.add("Grapes");
        
        System.out.println("Fruits before we change index 2");
        System.out.println(fruits);
        
        //Change the item at index 2 to Apple
        fruits.set(2, "Apple");
        
        System.out.println("");
        System.out.println("Fruits after we change index 2");
        System.out.println(fruits);
    }
}

The following is the output of the code.

Fruits before we change index 2
[Cucumbers, Peach, Grapes, Guava, Kiwi, Grapes]

Fruits after we change index 2
[Cucumbers, Peach, Apple, Guava, Kiwi, Grapes]

We can also add items at a particular index using the add() method and provide two parameters i.e. the index and the item.

Let’s see the example below.

import java.util.ArrayList;
class SimpleArrayListExample {
    public static void main(String[] args) {
        // Creating an ArrayList of String
        ArrayList<String> fruits = new ArrayList<>();
        //Adding items to ArrayList
        fruits.add("Cucumbers");
        fruits.add("Peach");
        fruits.add("Grapes");
        fruits.add("Guava");
        fruits.add("Kiwi");
        fruits.add("Grapes");
        
        System.out.println("Fruits before we add item at index 2");
        System.out.println(fruits);
        
        //Add a new item at index 2
        fruits.add(2, "Apple");
        
        System.out.println("");
        System.out.println("Fruits after we add item at index 2");
        System.out.println(fruits);
    }
}

The following is the output of the code.

run:
Fruits before we add item at index 2
[Cucumbers, Peach, Grapes, Guava, Kiwi, Grapes]

Fruits after we add item at index 2
[Cucumbers, Peach, Apple, Grapes, Guava, Kiwi, Grapes]

Conclusion

That’s all folks. In this article, you learned what a Java ArrayList is, how to use it, and what operations you can apply to it.

Thank you for reading. Please share with your friends with links below. See you in the next post.



Bessy
Eric Murithi

Life is beautiful, time is precious. Make the most out of it.

Get Programming and Technology Tips for Beginners.