Salty Egg
Salty Egg

Reputation: 185

Java - Is it safe to do deepCopy of UUID field as this.uuid = original.getUUID()?

For the following class, when I do deep copy, is it safe to write code as

this.id = original.getId();

In my test, it seems OK, as when I want to update the UUID field, I always assign it with a new UUID instance(I couldn't find any function which can modify an existing UUID instance). In this case, this copied one will never have side effect to original instance.

public class Container {

    private Type type;
    private UUID id;
    private Container c;

    // public constructors here

    protected Container(Container original, boolean deepCopy) {
        this.type = original.getType();
        this.id = original.getId();
        // for deep copy of id field, should I write as:
        // this.id = new UUID(original.getId().getMostSignificantBits(), original.getId().getLeastSignificantBits());
        if (original.getC() != null) {
            this.c = deepCopy ? original.getC().deepCopy() : original.getC();
        }
    }

    // getter and setter here

    public Container deepCopy() {
        return new Container(this, true);
    }

}

However in the project I maintained now(Not created by me), I find the deep copy code is as this:

this.id = new UUID(original.getId().getMostSignificantBits(), original.getId().getLeastSignificantBits());

No doubt, this is a correct solution.

My question is: is it safe to do this as

this.id = original.getId();

Maybe this is a stupid question, thanks for your time to help me.

Upvotes: 5

Views: 2131

Answers (2)

Bohemian
Bohemian

Reputation: 425198

A "deep copy" means that every object in your object tree is a new instance. By executing

this.id = original.getId();

you are using the same UUID object as the original object.

The code you found is how you make a copy of the UUID object such that it has the same value. It is unnecessary to copy a UUID for safety, as the UUID class is immutable; from its javadoc:

A class that represents an immutable universally unique identifier (UUID).

However there may be other considerations that support making a copy.

Upvotes: 2

GreyBeardedGeek
GreyBeardedGeek

Reputation: 30088

Yes, it's safe. UUID is immutable.

As you observed, you never modify the instance, you just assign a new instance to your member. So, you never effect any other code's UUID, even if they originally had a reference to the same one that you have.

The 'copy' code is totally unneccessary.

Upvotes: 5

Related Questions