Append all elements of another Collection to a Vector in Java


The elements of a Collection can be appended at the end of the Vector using the method java.util.Vector.addAll(). This method takes a single parameter i.e. the Collection whose elements are added to the Vector and it returns true if the Vector is changed.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.Vector;
public class Demo {
   public static void main(String args[]) {
      Vector vec1 = new Vector();
      vec1.add(7);
      vec1.add(3);
      vec1.add(5);
      vec1.add(9);
      vec1.add(2);
      System.out.println("The Vector vec1 elements are: " + vec1);
      Vector vec2 = new Vector();
      vec2.add(1);
      vec2.add(8);
      vec2.add(6);
      vec2.addAll(vec1);
      System.out.println("The Vector vec2 elements are: " + vec2);
   }
}

The output of the above program is as follows −

The Vector vec1 elements are: [7, 3, 5, 9, 2]
The Vector vec2 elements are: [1, 8, 6, 7, 3, 5, 9, 2]

Now let us understand the above program.

First, the Vector vec1 is defined and elements are added using the Vector.add() method. Then Vector vec1 is displayed. A code snippet which demonstrates this is as follows −

Vector vec1 = new Vector();
vec1.add(7);
vec1.add(3);
vec1.add(5);
vec1.add(9);
vec1.add(2);
System.out.println("The Vector vec1 elements are: " + vec1);

Then the Vector vec2 is defined and elements are added using the Vector.add() method. After that the Vector.addAll() method is used to append all the vec1 elements at the end of vec2. Then Vector vec2 is displayed. A code snippet which demonstrates this is as follows −

Vector vec2 = new Vector();
vec2.add(1);
vec2.add(8);
vec2.add(6);
vec2.addAll(vec1);
System.out.println("The Vector vec2 elements are: " + vec2);

Updated on: 30-Jun-2020

110 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements