How to Insert all the Collection Elements to the Specified Position in Java ArrayList?
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).
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.
ArrayList<String> ArrList =
"The ArrayList is : "
Vector<String> vector =
"List after addition of element at specific index : "
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!