How to Copy Elements from a Vector Collection in Java


This tutorial will show us how to copy all elements of one Java Vector object to another Java Vector object with copy method of Collections class.

Source Code

package com.beginner.examples;

import java.util.Collections;
import java.util.Vector;

public class CopyElementsToVector {

	public static void main(String[] args) {

		Vector vector = new Vector();
		// Add elements
		vector.add("A");
		vector.add("F");
		vector.add("J");
		vector.add("Y");

		// First way: when creating a new Vector object, specify the elements as
		// those in the old collection
		Vector copyVector_1 = new Vector(vector);

		/*
		 * The second way: create a new Vector collection and specify the same
		 * size as the old one, making the copy() method in the Collections
		 * tools class copy into the new Vector collection
		 */
		Vector copyVector_2 = new Vector();
		copyVector_2.setSize(vector.size());

		Collections.copy(copyVector_2, vector);

		System.out.println("copyVector_1:" + copyVector_1 + "ncopyVector_2:"
				+ copyVector_2);

	}
}

Output:

copyVector_1:[A, F, J, Y]
copyVector_2:[A, F, J, Y]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments