English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Arrays

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collections

Java Set Collections

Java Input/Output (I/)

Java Reader/Writer

Java Other Topics

Java ArrayList

In this tutorial, we will learn about the Java ArrayList class. We will learn about different operations and methods of ArrayList through examples.

The ArrayList class is an implementation of the List interface, which allows us to create adjustable-size arrays.

Java Arrays vs ArrayList

In Java, we need to declare the size of the array first before we can use it. Once the size of the array is declared, it is difficult to change it.

To solve this problem, we can use the ArrayList class. The ArrayList class that exists in the java.util package allows us to create an adjustable-size array.

Unlike arrays, when we add or remove elements from an array list (an object of the ArrayList class), the array list can automatically adjust its capacity. Therefore, array lists are also known as dynamic arrays.

Create ArrayList

This is the method we can use to create an array list in Java:

ArrayList<Type> arrayList = new ArrayList<>();

Here, Type indicates the type of the array list. For example,

//Create an integer type arraylist
ArrayList<Integer> arrayList = new ArrayList<>();
//Create a string type arraylist
ArrayList<String> arrayList = new ArrayList<>();

In the above program, we used Integer and String. Here, Integer is the corresponding wrapper class for int type.

Wrapper classes are classes that wrap primitive data types. For example, the Integer class wraps the int type, the Float class wraps the Float type, etc.

Note:We cannot create an array list of primitive data types (such as int, float, char, etc.). Instead, we must use their corresponding wrapper classes.

For strings, String is a class and there is no wrapper class. Therefore, we use String as is.

We can also use the List interface to create an ArrayList. This is because the ArrayList class implements the List interface.

List<String> list = new ArrayList<>();

ArrayList methods

ArrayList provides various methods that allow us to perform array list operations.

Add element to ArrayList

1. Using add() method

To add a single element to an array list, we use the add() method. For example,

import java.util.ArrayList;
class Main {

    public static void main(String[] args){
        ArrayList<String> animals = new ArrayList<>();
        //Add element
        animals.add("Dog");
        animals.add("Cat");
        animals.add("Horse");
        System.out.println("ArrayList: "
) + animals);
    }
}

Output Result

ArrayList: [Dog, Cat, Horse]

2. Using index number

We can also use an index to add elements to an array list. For example,

import java.util.ArrayList;
class Main {

    public static void main(String[] args){
        ArrayList<String> animals = new ArrayList<>();
        //Add element
        animals.add(0,"Dog");
        animals.add(1,"Cat");
        animals.add(2,"Horse");
        System.out.println("ArrayList: "
) + animals);
    }
}

Output Result

ArrayList: [Dog, Cat, Horse]

3. Add elements of one array list to another array list

To add all elements of an array list to a new array list, use the addAll() method. For example,

import java.util.ArrayList;
class Main {

    public static void main(String[] args){
        ArrayList<String> mammals = new ArrayList<>();
        mammals.add("Dog");
        mammals.add("Cat");
        mammals.add("Horse");
        System.out.println("Mammals: \t" + mammals);
        ArrayList<String> animals = new ArrayList<>();
        animals.add("Crocodile");
        // Add all elements of mammals to animals
        animals.addAll(mammals);
        System.out.println("Animals: \t" + animals);
    }
}

Output Result

Mammals: [Dog, Cat, Horse]
Animals: [Crocodile, Dog, Cat, Horse]

Initialize ArrayList using asList()

Unlike arrays, we cannot directly initialize an array list. However, we can use the asList() method of the Arrays class to achieve the same effect.

To use the asList() method, we must first import the java.util.Arrays package.

For example,

import java.util.ArrayList;
import java.util.Arrays;
class Main {

    public static void main(String[] args) {

        //Create an array list
        ArrayList<String> animals = new ArrayList<>(Arrays.asList("Cat", "Cow", "Dog"));
        System.out.println("ArrayList: "
) + animals);
        //Access elements in the array list
        String element = animals.get(1;
        System.out.println("Access element: " + element);
    }
}

Output Result

ArrayList: [Cat, Cow, Dog]
Access element: Cow

In the above example, please note the following expression:

new ArrayList<>(Arrays.asList("Cat", "Cow", "Dog"));

Here, we first create a3An array of elements: "Cat", "Cow", and "Dog". Then, the asList() method is used to convert the array to an array list.

Access elements of ArrayList

1.Use get() method

To access the elements of an array list randomly, we use the get() method. For example,

import java.util.ArrayList;
class Main {

    public static void main(String[] args) {

        ArrayList<String> animals = new ArrayList<>();
        //Add elements to the array list
        animals.add("Dog");
        animals.add("Horse");
        animals.add("Cat");
        System.out.println("ArrayList: "
) + animals);
        //Get an element from the array list
        String str = animals.get(0);
        System.out.print("Element at index 0: " + str);
    }
}

Output Result

ArrayList: [Dog, Horse, Cat]
Element at index 0: Dog

2.Use iterator() method

To access the elements of an array list in order, we use the iterator() method. We must import the java.util.Iterator package to use this method. For example,

import java.util.ArrayList;
import java.util.Iterator;
class Main {

    public static void main(String[] args){
        ArrayList<String> animals = new ArrayList<>();
        //Add elements to the array list
        animals.add("Dog");
        animals.add("Cat");
        animals.add("Horse");
        animals.add("Zebra");
        //Create an Iterator object
        Iterator<String> iterate = animals.iterator();
        System.out.print("ArrayList: ");
        //Use the Iterator method to access elements
        while(iterate.hasNext()){
            System.out.print(iterate.next());
            System.out.print(", ");
        }
    }
}

Output Result

ArrayList: Dog, Cat, Horse, Zebra,

Note:

  • hasNext() - If there is a next element in the ArrayList, it returns true.

  • next()  -  Return the next element in the ArrayList

Change ArrayList element

To change the element of the ArrayList, we can use the set() method. For example,

import java.util.ArrayList;
class Main {

    public static void main(String[] args) {

        ArrayList<String> animals = new ArrayList<>();
        //Add elements to the array list
        animals.add("Dog");
        animals.add("Cat");
        animals.add("Horse");
        System.out.println("ArrayList: "
) + animals);
        //Change the element of the ArrayList
        animals.set(2, "Zebra");
        System.out.println("Modified ArrayList: "); + animals);
    }
}

Output Result

ArrayList: [Dog, Cat, Horse]
Modified ArrayList: [Dog, Cat, Zebra]

Delete ArrayList element

1Use the remove() method

To delete an element from the ArrayList, we can use the remove() method. For example,

import java.util.ArrayList;
class Main {

    public static void main(String[] args) {

        ArrayList<String> animals = new ArrayList<>();
        //Add elements to the array list
        animals.add("Dog");
        animals.add("Cat");
        animals.add("Horse");
        System.out.println("Initial ArrayList: "); + animals);
        //from index2delete element from
        String str = animals.remove(2;
        System.out.println("Final ArrayList: "); + animals);
        System.out.println("Delete element: "); + str);
    }
}

Output Result

Initial ArrayList: [Dog, Cat, Horse]
Final ArrayList: [Dog, Cat]
Delete element: Horse

2Use the removeAll() method

To delete all elements from the ArrayList, we use the removeAll() method. For example,

import java.util.ArrayList;
class Main {

    public static void main(String[] args) {

        ArrayList<String> animals = new ArrayList<>();
        // Add elements to ArrayList
        animals.add("Dog");
        animals.add("Cat");
        animals.add("Horse");
        System.out.println("Initial ArrayList: "); + animals);
        // Delete all elements
        animals.removeAll(animals);
        System.out.println("Final ArrayList: "); + animals);
    }
}

Output Result

Initial ArrayList: [Dog, Cat, Horse]
Final ArrayList: []

3Use the clear() method

We can also use the clear() method to delete all elements from the ArrayList. For example,

import java.util.ArrayList;
class Main {

    public static void main(String[] args) {

        ArrayList<String> animals = new ArrayList<>();
        //Add elements to the array list
        animals.add("Dog");
        animals.add("Cat");
        animals.add("Horse");
        System.out.println("Initial ArrayList: "); + animals);
        //Delete all elements
        animals.clear();
        System.out.println("Final ArrayList: "); + animals);
    }
}

Output Result

Initial ArrayList: [Dog, Cat, Horse]
Final ArrayList: []

Note:The clear() method is more efficient than the removeAll() method.

Traverse the ArrayList

1Use the for loop

import java.util.ArrayList;
class Main {

    public static void main(String[] args) {

        //Create an array list
        ArrayList<String> animals = new ArrayList<>();
        animals.add("Cow");
        animals.add("Cat");
        animals.add("Dog");
        System.out.println("ArrayList: "
) + animals);
        //Use the for loop
        System.out.println("Access all elements: ");
        for (int i = 0; i < animals.size(); i++) {
            System.out.print(animals.get(i));
            System.out.print(", ");
        }
    }
}

Output Result

ArrayList: [Cow, Cat, Dog]
Access all elements:
Cow, Cat, Dog,

2Use the forEach loop

import java.util.ArrayList;
class Main {

    public static void main(String[] args) {

        // Create an array list
        ArrayList<String> animals = new ArrayList<>();
        animals.add("Cow");
        animals.add("Cat");
        animals.add("Dog");
        System.out.println("ArrayList: "
) + animals);
        //Using forEach loop
        System.out.println("Access all elements: ")
        for(String animal : animals) {
            System.out.print(animal);
            System.out.print(", ");
        }
    }
}

Output Result

ArrayList: [Cow, Cat, Dog]
Access all elements:
Cow, Cat, Dog,

In the two examples, we have accessed each element of the array list using a loop.

Get the length of ArrayList

To get the length of an array list, we use the size() method. For example,

import java.util.ArrayList;
class Main {

    public static void main(String[] args) {

        ArrayList<String> animals = new ArrayList<>();
        // Add elements to the arrayList
        animals.add("Dog");
        animals.add("Horse");
        animals.add("Cat");
        System.out.println("ArrayList: "
) + animals);
        //Get the size of arrayList
        System.out.println("The size of arrayList: ") + animals.size());
    }
}

Output Result

ArrayList: [Dog, Horse, Cat]
The size of arrayList: 3

Sort the elements of ArrayList

To sort the elements of an array list, we use the sort() method of the Collections class. To use it, we must first import the java.util.Collections package.

By default, sorting is performed in ascending order of letters or numbers. For example,

import java.util.ArrayList;
import java.util.Collections;
class Main {

    public static void main(String[] args){
        ArrayList<String> animals = new ArrayList<>();
        //Add elements to the array list
        animals.add("Horse");
        animals.add("Zebra");
        animals.add("Dog");
        animals.add("Cat");
        System.out.println("Unsorted ArrayList: ") + animals);
        //Sort the array list
        Collections.sort(animals);
        System.out.println("Sorted ArrayList: ") + animals);
    }
}

Output Result

Unsorted ArrayList: [Horse, Zebra, Dog, Cat]
Sorted ArrayList: [Cat, Dog, Horse, Zebra]

For more information on sorting array lists, please visit Java ArrayList sort.

Java ArrayList to Array

In Java, we can use the toArray() method to convert an array list to an array. For example,

import java.util.ArrayList;
class Main {

    public static void main(String[] args) {

        ArrayList<String> animals = new ArrayList<>();
        //Add elements to the array list
        animals.add("Dog");
        animals.add("Cat");
        animals.add("Horse");
        System.out.println("ArrayList: "
) + animals);
        //Create a new String array
        String[] arr = new String[animals.size()];
        //Convert ArrayList to array
        animals.toArray(arr);
        System.out.print("Array: ");
        for(String item: arr) {

            System.out.print(item+", ");
        }
    }
}

Output Result

ArrayList: [Dog, Cat, Horse]
Array: Dog, Cat, Horse,

Java Array to ArrayList

We can also convert an array to an array list. To do this, we can use the asList() method of the Arrays class.

To use asList(), we must first import the java.util.Arrays package. For example,

import java.util.ArrayList;
import java.util.Arrays;
class Main {

    public static void main(String[] args) {

        //Create a string array
        String[] arr = {"Dog", "Cat", "Horse"};
        System.out.print("Array: ");
        //Print array
        for(String str: arr) {

            System.out.print(str);
            System.out.print(" ");
        }
        //Create ArrayList from array
        ArrayList<String> animals = new ArrayList<>(Arrays.asList(arr));
        System.out.println(
"ArrayList: "
) + animals);
    }
}

Output Result

Array: Dog, Cat, Horse
ArrayList: [Dog, Cat, Horse]

In the above program, we first created a String array arr.

Then, we use the asList() method to convert an array to an array list.

Java ArrayList to String

To convert an array list to a string, you can use the toString() method. For example

import java.util.ArrayList;
class Main {

    public static void main(String[] args) {

        ArrayList<String> animals = new ArrayList<>();
        //Add elements to ArrayList
        animals.add("Dog");
        animals.add("Cat");
        animals.add("Horse");
        System.out.println("ArrayList: "
) + animals);
        //Convert ArrayList to String
        String str = animals.toString();
        System.out.println("String: " + str);
    }
}

Output Result

ArrayList: [Dog, Cat, Horse]
String: [Dog, Cat, Horse]

Note: The toString() method converts the entire ArrayList to a single String.

Other ArrayList Methods

MethodContent Description
clone()

Create a new ArrayList with the same elements, size, and capacity.

contains()

Search for the specified element in the ArrayList and return a boolean value.

ensureCapacity()

Specify the total number of elements that the ArrayList can contain.

isEmpty()

Check if the ArrayList is empty.

indexOf()

Search for the specified element in the ArrayList and return the index of the element.

trimToSize()

Reduce the capacity of the ArrayList to the current size.