Search code examples
javauuiddeep-copy

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.


Solution

  • 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.