Vector

Insert all elements of Collection to specific Vector index

With this example we are going to demonstrate how to insert all elements of a Collection to specific Vector index, using the ArrayList as a Collection implementation. In short, to insert all elements of an ArrayList to a specific Vector index you should:

  • Create a new Vector.
  • Populate the vector with elements, with add(E e) API method of Vector.
  • Create a new ArrayList.
  • Populate the arrayList with elements, with add(E e) API method of ArrayList.
  • Invoke addAll(int index, Collection c) API method of Vector, using the arrayList as parameter. It inserts all of the elements in the specified arrayList into this Vector at the specified position and shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices). The new elements will appear in the Vector in the order that they are returned by the specified arrayList’s iterator.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;
 
import java.util.ArrayList;
import java.util.Vector;
 
public class InsertAllElementsOfCollectionToVector {
 
  public static void main(String[] args) {
 
    // Create a Vector and populate it with elements
    Vector vector = new Vector();
    vector.add("element_1");
    vector.add("element_2");
    vector.add("element_3");
 
    // Create another Collection e.g. ArrayList and populate it with elements
    ArrayList arrayList = new ArrayList();
    arrayList.add("arrayList_element_1");
    arrayList.add("arrayList_element_2");
 
    // Insert all elements of ArrayList to Vector at index 1
    vector.addAll(1,arrayList);
 
    System.out.println("Elements in Vector :");
    for(int i=0; i < vector.size(); i++)

System.out.println(vector.get(i));
 
  }
}

Output:

Elements in Vector :
element_1
arrayList_element_1
arrayList_element_2
element_2
element_3

 
This was an example of how to insert all elements of a Collection to specific Vector index in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button