Press "Enter" to skip to content

Java.util.ArrayList.add() Method

ArrayList add(int index, E element) method inserts the element E at the specified index. As a result, the element at that position and any subsequent elements are shifted to the right by 1 position in the List.

Syntax:

Following are the variations of the add() method.

 public boolean add(E e) 
Freshers Placement

It returns true on successful insertion.

public void add(int index, E e)

Parameters:

e – It is the element to insert to the list.
The index is the position where ‘e’ needs to be added.

Throws:
IndexOutOfBoundsException – If the index is out of range i.e (index < 0 OR index > size()).
Index starts at 0.

Example 1

This example shows how the ArrayList add() method appends the element to the end of the list.

import java.util.ArrayList;

// Java code to demonstrate 
// the use of add()
public class ArrayListDemo {

	public static void main(String[] args) {

		// create an arraylist
		ArrayList<Integer> arrList = new ArrayList<>();

		// add elements to the list, by default element
		// gets added to the end of the list
		arrList.add(10);
		arrList.add(20);
		arrList.add(30);
		arrList.add(40);

		for (Integer i : arrList) {
			System.out.println("Value is = " + i);
		}
	}
}

Output:

Value is = 10
Value is = 20
Value is = 30
Value is = 40

Example 2

Freshers Placement

This example shows how to insert an element in between the list using add(index, element)

import java.util.ArrayList;

// Demonstrate the use of add(index, element)
public class ArrayListDemo {

	public static void main(String[] args) {
		// create the list
		ArrayList<Integer> arrList = new ArrayList<>();

		// insert the elements
		arrList.add(50);
		arrList.add(60);
		arrList.add(70);

		// index starts from 0, element will be added at the second position
		arrList.add(2, 100);

		for (Integer i : arrList) {
			System.out.println("Value is = " + i);
		}
	}
}

Output:

Value is = 50
Value is = 60
Value is = 100
Value is = 70

Comments are closed.