Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quickest way to clone a GregorianCalendar?

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?

like image 277
wds Avatar asked Mar 23 '10 10:03

wds


2 Answers

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

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

like image 90
Bozho Avatar answered Sep 23 '22 15:09

Bozho


Specifically, the quickest line of code to copy a Calendar is:

GregorianCalendar newCalendar = (Calendar)(oldCalendar.clone()); 
like image 40
Everyone_Else Avatar answered Sep 22 '22 15:09

Everyone_Else