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); } } |
[1, 2, 3, 4]
Time Complexity: O(1)
Adding a new element at the end takes O(1) time on average.
Auxiliary Space: O(1)
As constant extra space is used.
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 // position(zero-based) list.add( 1 , 3 ); // 4 gets added to the 2nd // position(zero-based) list.add( 2 , 4 ); System.out.println(list); } } |
[1, 3, 4, 2]
Time Complexity: O(n)
Auxiliary Space: O(1)
As constant extra space is used.