Java shallow clone and deep clone

Source: Internet
Author: User

What are shallow clones and deep clones?
克隆顾名思义就是,参照一个东西再做一个出来浅克隆:直接复写Object的clone()方法,默认情况下8种基本数据类型和String都会进行深克隆,另外的其他引用类型为浅克隆(浅克隆:引用指向的是同一个对象)深克隆:浅克隆中那另外的其他引用类型都让其变为深克隆

Reference type plots

Shallow clone
public class Main {    public static void main(String[] args) throws Exception {        A a = new A();        A b = (A)a.clone();        b.str = "....";        b.i = 1000;        System.out.println(a == b); //false 表示地址并不一样,不是同一个引用        System.out.println(a.p == b.p); //true 表示引用类型只想的是同一个引用        System.out.println(a.str == b.str); //false 表示地址并不一样,不是同一个引用        System.out.println(a.i == b.i);    //false 表示地址并不一样,不是同一个引用    }}//克隆对象需要实现Cloneable接口class A implements Cloneable {    Person p = new Person("谭迪");    String str = "hehe";    int i = 100;    //浅克隆:该方法来自于Object    @Override    protected Object clone() throws CloneNotSupportedException {        return super.clone();    }}class Person{    String name;    public Person(String name) {        this.name = name;    }}
Deep clones
public class Main {    public static void main(String[] args) throws Exception {        A a = new A();        A b = (A)a.clone();        b.str = "....";        b.i = 1000;                System.out.println(a == b);         //false        System.out.println(a.p == b.p);     //flase        System.out.println(a.str == b.str); //flase        System.out.println(a.i == b.i);     //flase    }}//克隆对象需要实现Cloneable接口class A implements Cloneable {    Person p = new Person("小明");    String str = "hehe";    int i = 100;    //深克隆:该方法来自于Object    @Override    protected A clone() throws CloneNotSupportedException {        A a = (A)super.clone();        a.p = (Person)p.clone();        return a;    }}class Person implements Cloneable{    String name;    public Person(String name) { this.name = name; }    @Override    protected Object clone() throws CloneNotSupportedException {        return super.clone();    }}

Java shallow clone and deep clone

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.