Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clone() method in Java

Tags:

java

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?

like image 780
Tom Avatar asked Jun 17 '11 11:06

Tom


2 Answers

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;

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

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  |
                     '-----'
like image 135
Paŭlo Ebermann Avatar answered Oct 24 '22 07:10

Paŭlo Ebermann


An assignment copies the reference of an instance to a variable. A clone operation will clone the instance (and assign a reference to the clone).

With assignment, you'll end up with multiple variables pointing to one object, with cloning you'll have multiple variables that hold references of multiple objects.

SomeCloneable a = new SomeCloneable();
SomeCloneable b = a;                     // a and b point to the same object

/* versus */

SomeCloneable a = new SomeCloneable();
SomeCloneable b = a.clone();             // a and b point to the different objects
like image 43
Andreas Dolk Avatar answered Oct 24 '22 07:10

Andreas Dolk