Clone () method in Java

As far as I know, the method clone () enables us to copy objects in Java (no reference) But I've also read that copy. It's very shallow So what point? What kind of ability does the cloning () method give me? Isn't it a simple compliment?

Solution

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;

Changes on P3 are fed back to P, while changes on P2 are not fed back to P

Let's look at the situation after the individual statements (assuming that 1, 2, 5 and 7 will be the object):

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  |
                     '-----'
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>