Is clone() in java shallow copy?

2020-02-26 08:53发布

Is clone() in java a shallow copy?

Eventually this gets to the clone() method of Object (the uppermost class), which creates a new instance of the same class as the object and copies all the fields to the new instance (a "shallow copy").

I read this from wikipedia.

I don't understand why it is a shallow copy. clone() will create a new instance with all fields. Is this just a deep copy? confused. Need some explanation for me.

8条回答
贼婆χ
2楼-- · 2020-02-26 09:18

Yes.

But first you need that your class will implement Cloneable and throw exception

class A implements Cloneable{
    public int y;
    public B b;

    public A(){
        b = new B();
    }

    public static void main(String[] args) throws CloneNotSupportedException{
        A a = new A();
        A a2 = (A) a.clone();
        System.out.print(a.b==a2.b);
    }
}

Output: true

查看更多
该账号已被封号
3楼-- · 2020-02-26 09:21

The default Object.clone() is indeed a shallow copy. However, it's designed to throw a CloneNotSupportedException unless your object implements Cloneable.

And when you implement Cloneable, you should override clone() to make it do a deep copy, by calling clone() on all fields that are themselves cloneable.

查看更多
登录 后发表回答