Java.util.ArrayList.add() Method in Java
Improve
Below are the add() methods of ArrayList in Java:
- boolean add(Object o) : This method appends the specified element to the end of this list.
Parameters: object o: The element to be appended to this list. Exception: NA
// Java code to illustrate add(Object o)importjava.io.*;importjava.util.ArrayList;publicclassArrayListDemo {publicstaticvoidmain(String[] args){// create an empty array list with an initial capacityArrayList<Integer> arrlist =newArrayList<Integer>(5);// use add() method to add elements in the listarrlist.add(15);arrlist.add(20);arrlist.add(25);// prints all the elements available in listfor(Integer number : arrlist) {System.out.println("Number = "+ number);}}}Output:
Number = 15 Number = 20 Number = 25
- void add(int index, Object element) : This method inserts the specified element E at the specified position in this list.It shifts the element currently at that position (if any) and any subsequent elements to the right (will add one to their indices).
Parameters: index : The index at which the specified element is to be inserted. element : The element to be inserted. Exception: Throws IndexOutOfBoundsException if the specified index is out of range (index size()).
// Java code to illustrate// void add(int index, Object element)importjava.io.*;importjava.util.ArrayList;publicclassArrayListDemo {publicstaticvoidmain(String[] args){// create an empty array list with an initial capacityArrayList<Integer> arrlist =newArrayList<Integer>(5);// use add() method to add elements in the listarrlist.add(10);arrlist.add(22);arrlist.add(30);arrlist.add(40);// adding element 35 at fourth positionarrlist.add(3,35);// let us print all the elements available in listfor(Integer number : arrlist) {System.out.println("Number = "+ number);}}}Output:
Number = 10 Number = 22 Number = 30 Number = 35 Number = 40
Feeling lost in the vast world of Backend Development? It's time for a change! Join our Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Share your thoughts in the comments

