Java中的clone()方法 [英] clone() method in Java

查看:190
本文介绍了Java中的clone()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,方法 clone()使我们能够在Java中复制对象(无引用)。但我也读过,副本很浅。那有什么意义呢? clone()方法的哪种能力给了我一个简单的辅助呢?

as I understood, the method clone() gives us the ability to copy object (no refernce) in Java. But I also read, that the copy is shallow. So what the point? Which ability the clone() method gives me, that a simple assingment doesn't?

推荐答案

区别在于你可以在不修改原始对象的情况下修改克隆对象。

The difference is that you can modify the cloned object without modifying the original object.

Point p = new Point(1,2);
Point p2 = p.clone();
Point p3 = p;
p2.x = 5;
p3.y = 7;

p3 的更改确实反馈给 p ,而 p2 的更改则没有。

The change on p3 does feed back to p, while the change on p2 does not.

让我们看看各个陈述后的情况如何(假设 1 2 5 7 将是对象):

Let's see how the situation is after the individual statements (assuming 1, 2, 5, 7 would be objects):

Point p = new Point(1,2);

            .-----.    .-----.
 p  ----->  |  x -+--> |  1  |
            |     |    '-----'
            |     |    .-----.
            |  y -+--> |  2  |
            '-----'    '-----'


Point p2 = p.clone();

            .-----.    .-----.    .-----.
 p  ----->  |  x -+--> |  1  | <--+- x  |  <----- p2
            |     |    '-----'    |     |
            |     |    .-----.    |     |
            |  y -+--> |  2  | <--+- y  |
            '-----'    '-----'    '-----'

Point p3 = p;

            .-----.    .-----.    .-----.
 p  ----->  |  x -+--> |  1  | <--+- x  |  <----- p2
            |     |    '-----'    |     |
            |     |    .-----.    |     |
 p3 ----->  |  y -+--> |  2  | <--+- y  |
            '-----'    '-----'    '-----'


p2.x = 5;

            .-----.    .-----.    .-----.    .-----.
 p  ----->  |  x -+--> |  1  |    |  x -+--> |  5  |
            |     |    '-----'    |     |    '-----'
            |     |    .-----.    |     |
 p3 ----->  |  y -+--> |  2  | <--+- y  |  <----- p2
            '-----'    '-----'    '-----'


p3.y = 7;

            .-----.    .-----.    .-----.    .-----.
 p  ----->  |  x -+--> |  1  |    |  x -+--> |  5  |
            |     |    '-----'    |     |    '-----'
            |     |    .-----.    |     |
 p3 ----->  |  y  |    |  2  | <--+- y  |  <----- p2
            '--+--'    '-----'    '-----'
               |     .-----.
               '---> |  7  |
                     '-----'

这篇关于Java中的clone()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆