Home > Java > javaTutorial > body text

Shallow copy and deep copy in JAVA

黄舟
Release: 2016-12-20 13:31:43
Original
1369 people have browsed it

1. Concepts of Shallow Copy and Deep Copy

⑴Shallow copy (shallow clone)

All variables of the copied object contain the same values ​​as the original object, and all references to other objects still point to the original object. In other words, a shallow copy only copies the object in question, not the objects it refers to. ​​​

​​​

⑵Deep copy (deep clone)

All variables of the copied object contain the same values ​​as the original object, except those variables that reference other objects. Variables that reference other objects will point to the copied new objects, rather than the original referenced objects. In other words, deep copy copies all the objects referenced by the object to be copied.

2. Java's clone() method

⑴The clone method copies the object and returns it to the caller. Generally speaking, the clone() method satisfies:

①For any object x, there is x.clone() !=x//The cloned object is not the same object as the original object

②For any object x, There is x.clone().getClass()= =x.getClass()//The cloned object has the same type as the original object

③ If the equals() method of object x) should be established.

⑵Clone of objects in Java

①In order to obtain a copy of the object, we can use the clone() method of the Object class.

②Override the clone() method of the base class in the derived class and declare it as public.

③In the clone() method of the derived class, call super.clone().

④Implement the Cloneable interface in the derived class.

Please look at the following code:

class Student implements Cloneable

{

      String name;

This.name=name ;

This.age=age;

}

public Object clone()

{

Object o=null;

try

         o=(Student)super.clone();// clone() in Object identifies which

// object you want to copy. C}

Catch (ClonenotSupportedException E)

{

System.out.println (e.tostring ());

}

Return o;

}

(String[] args)

{

Student s1=new Student("zhangsan",18);

Student s2=(Student)s1.clone();

The above is the shallow copy and deep copy in JAVA Content, for more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!