Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java ArrayList clone() Method

Java ArrayList clone() Method

Java ArrayList Java ArrayList

The clone() method is used to copy a dynamic array; it is 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 block of memory, soif one of the objects changes this address, it will affect the other object..

The counterpart of a shallow copy is a deep copy; a deep copy completely copies an object out of memory, allocating a new area from the 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:

Return Value

Returns an ArrayList object.

Example

Copying a dynamic array using the ArrayList clone() method:

Example

import

java.util.ArrayList

;

class

Main

{

   

public

static

void

main

(

String

[

]

args

)

{

       

// Create an array

        ArrayList

<

String

sites

=

new

ArrayList

<>

(

)

;

        sites.

add

(

"Google"

)

;

        sites.

add

(

"Runoob"

)

;

        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 the above program is:


网站列表: [Google, Runoob, Taobao]
拷贝 ArrayList: [Google, Runoob, Taobao]

In the example above, we create a dynamic array named sites. Note the expression:

(ArrayList)sites.clone();

Output the return value of the clone() method

Example

import

java.util.ArrayList

;

class

Main

{

   

public

static

void

main

(

String

[

]

args

)

{

       

// Create an array

        ArrayList

<

String

sites

=

new

ArrayList

<>

(

)

;

        sites.

add

(

"Google"

)

;

        sites.

add

(

"Runoob"

)

;

        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 the above program is:


网站列表: [Google, Runoob, Taobao]
clone() 返回值: [Google, Runoob, Taobao]

In the example above, we created a dynamic array named sites. And here we output the return value of the clone() method.

**Note:** The clone() method is not a method specific to the ArrayList class. Any class that implements the Cloneable interface can use the clone() method.

Java ArrayList Java ArrayList