How to add element in ArrayList : add() Method Example

This is a tutorial for adding an element to the ArrayList in java.

The method signature of add method is
public boolean add(Object element)

According to Java docs, ArrayList add() method appends the specified element to the end of the list.

add() method ArrayList Example in Java


import java.util.*;
public class AddMethodExample {
    public static void main(String args[]) {



        //Declaration of String ArrayList 
        ArrayList<String> arrlist = new ArrayList<String>(); 
 
        //Example of add method for String ArrayList
        arrlist.add("California");
        arrlist.add("New York");
        arrlist.add("Boston");
        arrlist.add("San jose");
        arrlist.add("San Francisco");
        System.out.println("ArrayList Elements of String Type: "+ arrlist);

        //Example of add method for Integer ArrayList
        ArrayList<Integer> arrlist2 = new ArrayList<Integer>(); 
 
        //Example of add method for Integer ArrayList
        arrlist2.add(12);
        arrlist2.add(3);
        arrlist2.add(9);
        arrlist2.add(96);
        arrlist2.add(8);
        System.out.println("ArrayList Elements of Integer Type: "+arrlist2);
    }
}


Output


ArrayList Elements of String Type: [California, New York, Boston, San jose, San Francisco]
ArrayList Elements of Integer Type: [12, 3, 9, 96, 8]
 

That's all for the add(E e) method example of ArrayList class. Please mention in comments if you have any questions.

Reference:
ArrayList add(E e) method

About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry