Insert all Elements of Other Collection to Specified Index of Java ArrayList
ArrayList is part of the collection framework. It is a List and implements the java.util.list interface. ArrayList is a better alternative to Arrays, especially if you are not sure about the array size. Unlike array which has a fixed size, ArrayList can grow in size when needed. Internally ArrayList also uses arrays to store data. When it reaches the current capacity and needs to grow, a new array is created and elements are copied from the old array to the new array.
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.
Input : ArrayList = [a, b, c], Vector = [d, e] Output: collection = [a, b, c, d, e] Input : ArrayList = [1, 5, 6], Vector = [2, 3] Output: collection = [1, 2, 3, 5, 6]
- Create an ArrayList and add some elements in it
- Create a new collection, here we will create vector
- Add elements to an ArrayList using the addAll(index, list) method which inserts the list at the given index of this list.
addAll(int index,Collection c)
- index: The index at which the specified element is to be inserted.
- c: This is the collection containing elements to be added to this list
We can use this method to insert elements from a collection at the given index. All the elements in the list are shifted towards the right to make space for the elements from the collection.
Below is the implementation of the problem statement
Elements of ArrayList: [Australia, Brazil, France, Germany, India] Elements of Collection(Vector): [Canada, Denmark, Egypt] After inserting elements of other collection elements of ArrayList: [Australia, Brazil, Canada, Denmark, Egypt, France, Germany, India]