Java ArrayList add() Method Example

Thejava.util.ArrayList.add(E e) method appends the specified element E to the end of the list.

ArrayListadd() method is used to add an element in the list. We can add elements of any type in ArrayList, but make the program behave in a more predictable manner, we should add elements of one certain type only in any given list instance.

Java ArrayList add() Method Example

The following example shows the usage ofjava.util.ArrayList.add(E) method:

importjava.util.ArrayList;importjava.util.List;// How to create an ArrayList using the ArrayList() constructor.// Add new elements to an ArrayList using the add() method.publicclassCreateArrayListExample {publicstaticvoidmain(String[]args) {// Creating an ArrayList of String usingList<String> fruits=newArrayList<>();// Adding new elements to the ArrayList     fruits.add("Banana");     fruits.add("Apple");     fruits.add("mango");     fruits.add("orange");System.out.println(fruits);    }}
Let us compile and run the above program, this will produce the following result −
[Banana, Apple, mango, orange]

Java ArrayList add() Method Example - Insert element in specific position

import java.util.ArrayList;publicclassArrayListDemo{publicstaticvoid main(String[] args){// create an empty array list with an initial capacityArrayList<Integer> arrlist=newArrayList<Integer>(5);// use add() method to add elements in the list      arrlist.add(15);      arrlist.add(22);      arrlist.add(30);      arrlist.add(40);// adding element 25 at third position      arrlist.add(2,25);// let us print all the elements available in listfor(Integer number: arrlist){System.out.println("Number = "+ number);}}}
Let us compile and run the above program, this will produce the following result −
Number = 15Number = 22Number = 25Number = 30Number = 40

Java ArrayList Source Code Examples


Comments