Sunday, November 17, 2024
Google search engine
HomeLanguagesJavaInsert all Elements of Other Collection to Specified Index of Java ArrayList

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:

  1. Create an ArrayList and add some elements in it
  2. Create a new collection, here we will create vector
  3. 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:

  1. index: The index at which the specified element is to be inserted.
  2. 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




// Insert all Elements of Other Collection
// to Specified Index of Java ArrayList
import java.util.*;
public class GFG {
    public static void main(String arg[])
    {
        // Creating ArrayList
        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);
  
        // Creating collection of vector
  
        Vector<String> obj2 = new Vector<String>();
  
        obj2.add("Canada");
  
        obj2.add("Denmark");
  
        obj2.add("Egypt");
  
        System.out.println(
            "Elements of Collection(Vector): " + obj2);
  
        // inserting all Elements of Other Collection to
        // Specified Index of ArrayList
        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]
RELATED ARTICLES

Most Popular

Recent Comments