Skip to content

How to Clone, Copy, or Append Vector in Java Example

This example shows how to clone, copy, or append Vector in Java. This example also shows how to clone, append one vector to another, and copy vector using constructor, addAll method, and clone method.

How to clone, copy, or append one Vector to another in Java?

There are several ways using which we can copy one vector to another in Java.

1. Using the constructor

The Vector class provides a constructor that accepts a collection object as a parameter.

It creates a new vector object containing all the elements of the specified collection object. We can use this constructor to copy one vector object to another as given below.

Output

2. Copy or append one vector to another using the addAll method

The Vector addAll method adds all elements of the specified collection object to this vector object.

It returns true if this vector object is changed as a result of this method call.

We can use this method to append elements of one vector to another or copy a vector.

Output

3. Using the clone method

The Vector clone method returns a clone of this vector object.

Output

Important Note:

All of the above given approaches create a shallow copy of the vector object. That means only the element object references are copied, not the actual objects.

If you change the element object, the change will be reflected in the original as well as cloned or copied vector object as shown below.

Output

This example is a part of the Java Vector Tutorial with Examples.

Please let me know your views in the comments section below.

References:
Java 8 Vector Documentation

About the author

Leave a Reply

Your email address will not be published.