Java ArrayList - add() Method
The java.util.ArrayList.add() method is used to add a new element at the end of the ArrayList.
Syntax
public boolean add(E element)
Here, E is the type of element maintained by the container.
Parameters
element |
Specify element which need to be added in the ArrayList. |
Return Value
Returns true if the element is successfully added, else returns false.
Exception
NA
Example:
In the example below, the java.util.ArrayList.add() method is used to add new element at the end of 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 using add() method MyList.add(10); MyList.add(20); MyList.add(30); MyList.add(40); MyList.add(50); //printing ArrayList System.out.println("MyList contains: " + MyList); } }
The output of the above code will be:
MyList contains: [10, 20, 30, 40, 50]
Example:
Lets consider one more example where string elements are added 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("MON"); MyList.add("TUE"); MyList.add("WED"); MyList.add("THU"); MyList.add("FRI"); //printing ArrayList System.out.println("MyList contains: " + MyList); } }
The output of the above code will be:
MyList contains: [MON, TUE, WED, THU, FRI]
❮ Java.util - ArrayList