Vector

Append all elements of a Collection to Vector example

This is an example of how to append all elements of a Collection to a Vector. We are using an ArrayList as a Collection implementation. Appending all elements of an ArrayList to a Vector implies that 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(Collection c) API method of Vector. It appends all of the elements in the specified arrayList to the end of this Vector, in the order that they are returned by the arrayList’s Iterator. The behavior of this operation is undefined if the arrayList is modified while the operation is in progress.

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

package com.javacodegeeks.snippets.core;
 
import java.util.Vector;
import java.util.ArrayList;
 
public class AppendAllElementsOfCollectionToVector {
 
  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");
 
    // Append all elements of ArrayList to Vector using the boolean addAll(Collection c) operation
    vector.addAll(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
element_2
element_3
arrayList_element_1
arrayList_element_2

 
This was an example of how to append all elements of a Collection to a Vector 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