Java ArrayList - add() Method
The java.util.ArrayList.add() method is used to insert the specified element at specified index in the ArrayList. The method shifts the current element at the specified position (if any) and any subsequent elements to the right by adding one to their indices. Addition of new element results into increasing the ArrayList size by one.
Syntax
public void add(int index, E element)
Here, E is the type of element maintained by the container.
Parameters
index |
Specify index number at which new element need to be inserted in the ArrayList. |
element |
Specify element which need to be inserted in the ArrayList. |
Return Value
void type.
Exception
Throws IndexOutOfBoundsException, if the index is out of range.
Example:
In the example below, the java.util.ArrayList.add() method is used to insert new element at specified position in the ArrayList.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a ArrayList ArrayList<Integer> MyList = new ArrayList<Integer>(); //populating ArrayList MyList.add(10); MyList.add(20); MyList.add(30); //inserting new element in the ArrayList MyList.add(1,100); System.out.println("MyList contains: " + MyList); //inserting new element in the ArrayList MyList.add(0,500); System.out.println("MyList contains: " + MyList); } }
The output of the above code will be:
MyList contains: [10, 100, 20, 30] MyList contains: [500, 10, 100, 20, 30]
Example:
Lets consider one more example where string elements are inserted at given position in the given ArrayList.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a ArrayList ArrayList<String> MyList = new ArrayList<String>(); //populating ArrayList using add() method MyList.add("WED"); MyList.add("THU"); MyList.add("FRI"); //displaying the content of the ArrayList System.out.println("MyList contains: " + MyList); //inserting new element in the ArrayList MyList.add(0,"TUE"); MyList.add(0,"MON"); //displaying the content of the ArrayList System.out.println("MyList contains: " + MyList); } }
The output of the above code will be:
MyList contains: [WED, THU, FRI] MyList contains: [MON, TUE, WED, THU, FRI]
❮ Java.util - ArrayList