Java Vector clone() Method
Last Updated : 14 Jan, 2025
Improve
In Java, the clone() method of the Vector class is used to return a shallow copy of the vector. It just creates a copy of the vector. The copy will have a reference to a clone of the internal data array but not a reference to the original internal data array.
Example 1: In this example, we use the clone() method to create the shallow copy of a vector of integer type.
// Demonstrating the use of clone() method
// with a Vector of Integer type
import java.util.Vector;
class Geeks {
public static void main(String[] args)
{
// Creating a vector
Vector<Integer> v = new Vector<>();
// using add() to insert elements in the vector
v.add(100);
v.add(200);
v.add(300);
System.out.println("The Original Vector is: " + v);
// Cloning the original vector
Vector<Integer> cv = (Vector<Integer>)v.clone();
// Displaying the cloned vector
System.out.println("The Cloned Vector is: " + cv);
}
}
Output
The Original Vector is: [100, 200, 300] The Cloned Vector is: [100, 200, 300]
Syntax of Vector clone()
Method
public Object clone()
Return Type: It returns an object which is just the copy of the vector.
Example 2: In this example, we create a shallow copy of a vector of string type.
// Demonstrating the use of clone() method
// with a Vector of String type
import java.util.Vector;
public class Geeks {
public static void main(String args[])
{
// Creating a vector
Vector<String> v = new Vector<String>();
// using add() method to insert
// elements in the vector
v.add("Geeks");
v.add("For");
v.add("Geeks");
System.out.println("The Original Vector is: " + v);
// Cloning the Original vector
Vector<String> cv = (Vector<String>)v.clone();
// Displaying the Cloned vector
System.out.println("The Cloned Vector is: " + cv);
}
}
Output
The Original Vector is: [Geeks, For, Geeks] The Cloned Vector is: [Geeks, For, Geeks]
Example 3: To better understand shallow copying, here’s an example using a vector containing mutable objects.
// Demonstrating the use of clone() method with
// a Vector of StringBuilder objects
import java.util.Vector;
public class Geeks {
public static void main(String[] args) {
// Creating a vector of StringBuilder objects
Vector<StringBuilder> vec = new Vector<>();
vec.add(new StringBuilder("Hello"));
vec.add(new StringBuilder("Geeks"));
System.out.println("The Original Vector is: " + vec);
// Cloning the original vector
Vector<StringBuilder> cv = (Vector<StringBuilder>) vec.clone();
System.out.println("The Cloned Vector is: " + cv);
// Modifying an element in the original vector
vec.get(0).append(" Java");
System.out.println("After modification: ");
System.out.println("The Original Vector is: " + vec);
System.out.println("The Cloned Vector is: " + cv);
}
}
Output
The Original Vector is: [Hello, Geeks] The Cloned Vector is: [Hello, Geeks] After modification: The Original Vector is: [Hello Java, Geeks] The Cloned Vector is: [Hello Java, Geeks]