Java ArrayList clone() Method
The clone() method is used to copy an ArrayList, and it belongs to a shallow copy.
Extension:
A shallow copy only copies the pointer to an object, not the object itself. The new and old objects still share the same memory, soif one of the objects changes this address, it will affect the other object.。。
The counterpart of shallow copy is deep copy. Deep copy copies an object completely from memory, allocating a new area in heap memory to store the new object, andmodifying the new object will not affect the original object.。
The syntax of the clone() method is:
arraylist.clone()
Note:arraylist is an object of the ArrayList class.
Parameter description:
- None
Return Value
Returns the ArrayList object.
Example
Use the ArrayList clone() method to copy an ArrayList:
Example
class Main {
public static void main(String[] args){
// Create an array
ArrayList<String> sites = new ArrayList<>();
sites.add("Google");
sites.add("Example");
sites.add("Taobao");
System.out.println("Website list: " + sites);
// Copy sites
ArrayList<String> cloneSites = (ArrayList<String>)sites.clone();
System.out.println("Copied ArrayList: " + cloneSites);
}
}
The output of running the above program is:
网站列表: [Google, Example, Taobao] 拷贝 ArrayList: [Google, Example, Taobao]
In the above example, we create an ArrayList named sites. Note the expression:
(ArrayList<String>)sites.clone();
- sites.clone()- returns the copied sites object
- (ArrayList <String>)- converts the returned value into an ArrayList of type String
Output the return value of the clone() method
Example
class Main {
public static void main(String[] args){
// Create an array
ArrayList<String> sites = new ArrayList<>();
sites.add("Google");
sites.add("Example");
sites.add("Taobao");
System.out.println("Website list: " + sites);
// Output the value returned by the clone() method
System.out.println("clone() return value: " + sites.clone());
}
}
The output of running the above program is:
网站列表: [Google, Example, Taobao] clone() 返回值: [Google, Example, Taobao]
In the above example, we created an ArrayList named sites. And here we output the return value of the clone() method.
Note:The clone() method is not a specific method of the ArrayList class. Any class that inherits the Cloneable interface can use the clone() method.
Other extensions
Java ArrayList