Skip to content
Related Articles

Related Articles

How to Add Element in Java ArrayList?
  • Last Updated : 02 Mar, 2021

Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but there is no size limit. We can add or remove elements anytime. So, it is much more flexible than the traditional array.

Element can be added in Java ArrayList using add() method of java.util.ArrayList class.

1. boolean add(Object element):

The element passed as a parameter gets inserted at the end of the list.

Declaration:



public boolean add(Object element)

Parameter: 

The element will get added to the end of the list.

Return Value: 

This method returns a boolean value true

Example:

Input:
list.add("A");
list.add("B");
list.add("C");
Output:
list=[A,B,C]

Input:
list.add(1);
list.add(2);
list.add(3);
list.add(4);
Output:
list=[1,2,3,4]

Implementation of the given method:

Java




// Java program to add elements in
// Array List using add() method
 
import java.io.*;
import java.util.ArrayList;
 
class GFG {
    public static void main(String[] args)
    {
        ArrayList<Integer> list = new ArrayList<>();
 
        // add method for integer ArrayList
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        System.out.println(list);
    }
}
Output
[1, 2, 3, 4]

2. void add(int index, Object element)



The specified element gets inserted into the specified index.

Declaration:

public void add(int index, Object element)

Parameter: 

  • index – the position at which the element has to be inserted
  • element – the element to be inserted.

Exception: It throws IndexOutOfBoundsException if index<0||index>size()

Example:

Input:
list.add("A");
list.add("B");
list.add(1,"C");
Output:
list=["A","C","B"]


Input:
list.add(1);
list.add(2);
list.add(1,3);
list.add(2,4);
Output:
list=[1,3,4,2]

Implementation of the given method:

Java




// Java program to add elements
// at the specified index in the list
// using add(index,element) method
 
import java.io.*;
import java.util.ArrayList;
 
class GFG {
    public static void main(String[] args)
    {
        ArrayList<Integer> list = new ArrayList<>();
 
        // add method for integer ArrayList
        list.add(1);
        list.add(2);
 
        // index is zero based
        // 3 gets added to the 1st
        // positon(zero-based)
        list.add(1, 3);
 
        // 4 gets added to the 2nd
        // position(zero-based)
        list.add(2, 4);
 
        System.out.println(list);
    }
}
Output
[1, 3, 4, 2]

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :