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.