Java Vector clone() Example

The clone() method of java.util.Vector class will create a shallow copy of the Vector.

Signature

public Object clone()

This method creates a shallow copy of this Vector. The elements themselves are not cloned.

Example

The following example shows the usage of java.util.Vector.clone() method.

import java.util.Vector;

public class CloneMethodVectorExample {
    public static void main(String args[]) {
        // create an empty Vector
        Vector vector1 = new Vector();
        

        // use add() method to add elements to the Vector
        vector1.add("Element1");
        vector1.add("Element2");
        vector1.add("Element3");

        // Printing the elements of the Vector vector1
        System.out.println("Elements of the vector1");
        for (String temp : vector1) {
            System.out.println(temp);
        }

        // create another empty Vector
        Vector vector2 = new Vector();
        // Shallow copying of vector1 to vector2
        vector2 = (Vector) vector1.clone();

        // Printing the elements of the Vector vector2
        System.out.println("Elements of the vector2");
        for (String temp : vector2) {
            System.out.println(temp);
        }
    }
}

Output

Elements of the vector1
Element1
Element2
Element3
Elements of the vector2
Element1
Element2
Element3

Leave a Reply

Your email address will not be published. Required fields are marked *