The element can be inserted at the collection elements to the specified position in ArrayList using Collection.addAll() method which is present in java.util.ArrayList class. If any element present at the index then that element and all its right side elements are shifted to the right side. this method accepts two arguments the first argument is the index where we want to insert the elements and the second argument is the object of another collection. This method returns a boolean value true if elements are successfully inserted else returns false.
addAll(Collection c) : This method appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s Iterator. The behavior of this operation is undefined if the specified collection is modified while the operation is in progress(implies that the behavior of this call is undefined if the specified collection is this list, and this list is nonempty).
Syntax:
public boolean addAll(int i, Collection c);
Exception: This method throws NullPointerException if elements contain one or more null values and c does not permit null elements, or if c or elements are null
Exception: Here two types of exceptions are possible.
- IndexOutOfBoundsException − If the index is out of range then it will show Index Out of Bounds Exception.
- NullPointerException − If the specified collection is null then it will show Null Pointer Exception.
CODE:
Java
import java.util.ArrayList;
import java.util.Vector;
public class GFG {
public static void main(String[] args)
{
ArrayList<String> ArrList = new ArrayList<String>();
ArrList.add( "Computer" );
ArrList.add( "Science" );
ArrList.add( "Portal" );
ArrList.add( "GeeksforGeeks" );
System.out.print( "The ArrayList is : " );
System.out.println(ArrList);
Vector<String> vector = new Vector<String>();
vector.add( "x" );
vector.add( "y" );
vector.add( "z" );
ArrList.addAll( 1 , vector);
System.out.println(
"List after addition of element at specific index : " );
System.out.println(ArrList);
}
}
|
Output
The ArrayList is : [Computer, Science, Portal, GeeksforGeeks]
List after addition of element at specific index :
[Computer, x, y, z, Science, Portal, GeeksforGeeks]
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
22 Nov, 2022
Like Article
Save Article