This seems elementary, but I must be missing something:
How to I return a deep copy of an object? For example the following code
looks legit to me, but the compiler complains that clone() has protected
access in java.lang.Object.
class DB
{
private BigInteger serialCounter;
public DB() { serialCounter = new BigInteger(); }
private synchronized BigInteger getNextSerialValue()
{
serialCounter = serialCounter.add( BigInteger.ONE );
return serialCounter.clone();
}
}
~S
Eric Sosman - 07 Apr 2005 16:49 GMT
> This seems elementary, but I must be missing something:
> How to I return a deep copy of an object? For example the following code
[quoted text clipped - 12 lines]
> }
> }
Roughly speaking, you can only clone an object with the
object's cooperation. The object indicates its willingness
to cooperate by implementing the Cloneable interface (which
BigInteger does not).
Instead of trying to clone the BigInteger, you could
construct a new one with the same value:
return new BigInteger(serialCounter.toByteArray());
However, all this copying seems pretty pointless. The
BigInteger object is immutable, so its value won't change
after it's created. When you "increment" serialCounter
you are not changing the value of an existing BigInteger;
rather, add() gives you a fresh BigInteger with the new
value. Thus, you can simply
return serialCounter;
without all the bother. (With this in mind, note that you
could initialize serialCounter to BigInteger.ZERO instead
of creating a redundant zero-valued object; a zero is a
zero is a zero.)

Signature
Eric.Sosman@sun.com
sanjay manohar - 07 Apr 2005 16:49 GMT
BigIntegers are immutable. Why would you need a clone?
PS what does the constructor "new BigInteger()" create? perhaps you
meant BigInteger.ZERO.
Shea Martin - 07 Apr 2005 20:26 GMT
> This seems elementary, but I must be missing something:
> How to I return a deep copy of an object? For example the following
[quoted text clipped - 14 lines]
>
> ~S
Immutable. I get it.
Thanks,
~S