Java ArrayList.add()

To add an element to an ArrayList in Java, we can use add() method of ArrayList class. add() method has two variations based on the number of arguments.

In this tutorial, we will learn about the Java ArrayList.add(element) and ArrayList.add(index, element) methods, with the help of syntax and examples.

add(index, element)

ArrayList.add() inserts the specified element at the specified position in this ArrayList.

ADVERTISEMENT

Syntax

The syntax of add() method with index and element as arguments is

ArrayList.add(int index, E element)

where

ParameterDescription
indexThe index at which the specified element is to be inserted in this ArrayList.
elementThe element to be inserted in this ArrayList.

Returns

The method returns void.

Example 1 – add(index, element)

In this example, we will take an ArrayList of Strings initialized with four elements. We then use add(index, element) method to insert String "k" at index 3.

Java Program

import java.util.ArrayList;
import java.util.Arrays;

public class Example {  
	public static void main(String[] args) {
		ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList("a", "b", "c", "d"));
		System.out.println("ArrayList before add : " + arrayList);
		
		int index = 3;
		String element = "k";
	    arrayList.add(index, element);	    
	    System.out.println("ArrayList before add : " + arrayList);
    }  
}

Output

ArrayList before add : [a, b, c, d]
ArrayList before add : [a, b, c, k, d]

add(E element)

ArrayList.add() appends the specified element to the end of this ArrayList.

Syntax

The syntax of add() method with element as argument is

ArrayList.add(E element)

where

ParameterDescription
elementThe element to be appended to this ArrayList.

Returns

The method returns boolean

Example 2 – add(element)

In this example, we will take an ArrayList of Strings initialized with four elements. We then use add(element) method to append the String "k" at the end of this ArrayList.

Java Program

import java.util.ArrayList;
import java.util.Arrays;

public class Example {  
	public static void main(String[] args) {
		ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList("a", "b", "c", "d"));
		System.out.println("ArrayList before add : " + arrayList);
		
		String element = "k";
	    arrayList.add(element);	    
	    System.out.println("ArrayList before add : " + arrayList);
    }  
}

Output

ArrayList before add : [a, b, c, d]
ArrayList before add : [a, b, c, d, k]

Conclusion

In this Java Tutorial, we have learnt the syntax of Java ArrayList.add() method, and also learnt how to use this method with the help of examples.