views:

135

answers:

1

I'm trying to make a deep copy of an object, including a GregorianCalendar instance. I'm always wary of using clone() and it doesn't seem to have been overridden here, so I'm just doing the copy field by field. Ideally, there'd be a copy constructor, which I could use like so:

GregorianCalendar newCalendar = new GregorianCalendar(oldCalendar);

Unfortunately I can't find any such functionality in the API and am stuck trying to figure out which fields I need to get an exact copy. So, to make a copy of one of these calendars, how would you do it? Am I missing some simple shortcut here?

+2  A: 

java.util.Calendar has overridden clone() which is working, so use it. Furthermore, Calendar doesn't have deep data hierarchy - its data are mainly ints.

To extend the answer, you can call SerializationUtils.clone(..) (from commons-lang) on any object which makes a deep copy, if the whole data hierarchy implements Serializable

Bozho
I wasn't quite clear on why I'm avoiding `clone()`. In this case I'm just following advice from Joshua Bloch on making defensive copies. Since clone() could conceivably be calling a subclass clone() method I could end up with a non-clean copy. A bit academic in my case, but that's why I was avoiding it.
wds
as I said, the data in the Calendar isn't affected by this problem - all its data is primitive. And the clone method in `Calendar` works fine.
Bozho
His point is that you could conceivably make a subclass that keeps a reference to the original calendar instance and keeps that reference around. If, say, all setters would set values in the original instance instead of the new one, your "deep" copy will now be compromised.
wds
Yes, I have the book :)
Bozho