Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...