![]() |
VOOZH | about |
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:
[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:
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:
[1, 3, 4, 2]
Time Complexity: O(n)
Auxiliary Space: O(1)
As constant extra space is used.