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.
Example:
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]
Approach:
- 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.
Syntax:
addAll(int index,Collection c)
Parameters:
- 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
Description:
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
Java
import java.util.*;
public class GFG {
public static void main(String arg[])
{
ArrayList<String> obj1 = new ArrayList<String>();
obj1.add( "Australia" );
obj1.add( "Brazil" );
obj1.add( "France" );
obj1.add( "Germany" );
obj1.add( "India" );
System.out.println( "Elements of ArrayList: "
+ obj1);
Vector<String> obj2 = new Vector<String>();
obj2.add( "Canada" );
obj2.add( "Denmark" );
obj2.add( "Egypt" );
System.out.println(
"Elements of Collection(Vector): " + obj2);
obj1.addAll( 2 , obj2);
System.out.println(
"After inserting elements of other collection elements of ArrayList:\n"
+ obj1);
}
}
|
Output
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]
Last Updated :
28 Jan, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...