The clone() method of the Vector class is used to return a shallow copy of this vector provided by the Object class. 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.
Syntax:
Vector.clone()
Parameters: The method does not take any parameters.
Return Value: The method returns an Object which is just the copy of the vector.
Exception Thrown: CloneNotSupportedException: This exception is thrown if the object’s class does not support the Cloneable interface.
Example 1:
Java
import java.util.*;
public class GFG {
public static void main(String args[])
{
Vector<String> vec_tor = new Vector<String>();
vec_tor.add( "Welcome" );
vec_tor.add( "To" );
vec_tor.add( "Geeks" );
vec_tor.add( "For" );
vec_tor.add( "Geeks" );
System.out.println( "Vector: " + vec_tor);
Object copy_vector = vec_tor.clone();
System.out.println( "The cloned vector is: "
+ copy_vector);
}
}
|
Output
Vector: [Welcome, To, Geeks, For, Geeks]
The cloned vector is: [Welcome, To, Geeks, For, Geeks]
Example 2:
Java
import java.util.*;
public class VectorDemo {
public static void main(String args[])
{
Vector<Integer> vec_tor = new Vector<Integer>();
vec_tor.add( 10 );
vec_tor.add( 15 );
vec_tor.add( 30 );
vec_tor.add( 20 );
vec_tor.add( 5 );
System.out.println( "Vector: " + vec_tor);
Object copy_vector = (Vector)vec_tor.clone();
System.out.println( "The cloned vector is: " + copy_vector);
}
}
|
Output
Vector: [10, 15, 30, 20, 5]
The cloned vector is: [10, 15, 30, 20, 5]

Note: In the above examples we have cloned vectors by creating objects of Object class itself as it does provide clone() method. So if object classes are not supporting any cloneable interface then it will not allow to clone and copy vector elements so does it will throw CloneNotSupportedException.
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
08 Nov, 2021
Like Article
Save Article