Syntax error Java Program to insert all elements of other Collection to specified Index of ArrayList

Java Program to insert all elements of other Collection to specified Index of ArrayList



Let us first create an ArraList and add some elements to it −

ArrayList < String > arr = new ArrayList < String > ();
arr.add("50");
arr.add("100");
arr.add("150");
arr.add("200");
arr.add("250");
arr.add("300");

Now, create a new collection. We are creating Vector here −

Vector<String>vector = new Vector<String>();
vector.add("500");
vector.add("700");
vector.add("800");
vector.add("1000");

Now, we will append all the elements of the above Vector to our ArrayList beginning from index 3 −

arr.addAll(3, vector);

Example

 Live Demo

import java.util.ArrayList;
import java.util.Vector;
public class Demo {
   public static void main(String[] args) {
      ArrayList<String>arr = new ArrayList<String>();
      arr.add("50");
      arr.add("100");
      arr.add("150");
      arr.add("200");
      arr.add("250");
      arr.add("300");
      Vector<String>vector = new Vector<String>();
      vector.add("500");
      vector.add("700");
      vector.add("800");
      vector.add("1000");
      // gets added at index 3
      arr.addAll(3, vector);
      System.out.println("Result after append...");
      for (String str: arr)
         System.out.println(str);
   }
}

Output

Result after append...
50
100
150
500
700
800
1000
200
250
300
Updated on: 2019-07-30T22:30:25+05:30

106 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements