Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to set a Calendar c equal Calendar c2?

Tags:

java

I have:

Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY,1);
c.set(Calendar.MINUTE,23);
c.set(Calendar.SECOND,22);

Calendar c2 = Calendar.getInstance();

c2 = c ; // 

is this last statement correct if I want to set Calendar c2 equal to Calendar c ?

like image 948
ARMAGEDDON Avatar asked Apr 25 '13 12:04

ARMAGEDDON


2 Answers

Although c2 = c would appear to work, that's not what you want: both variables will be pointing to the same calendar instance. As the result of this assignment, any changes made to c will be in c2 as well, and vice versa.

You can use clone() method to make a copy of the Calendar object, like this:

Calendar c= (Calendar)c2.clone();
like image 90
Sergey Kalinichenko Avatar answered Nov 14 '22 21:11

Sergey Kalinichenko


This statement:

c2 = c ; 

will copy the value of c into c2. The value of c is not a Calendar object - it's a reference. After this statement, the two variables have the same value - two references to the same object. Any changes to the Calendar object can be observed via either variable.

It's like giving two different people pieces of paper giving your home address - if one person uses the address to get to your house and paints the front door green, then the other person will see that too.

Note that this isn't Calendar-specific - this is the behaviour of assignment for all classes in Java.

(It's very important to distinguish between variables, references and objects, basically. In normal discussion the three are often used incorrectly for the sake of brevity, but you need to be able to tell the difference when you need to.)

Note that this code:

Calendar c2 = Calendar.getInstance();
c2 = c;

is creating a new Calendar instance pointlessly. It would be written more sensibly as:

Calendar c2 = c;

That code will have the same visible effect, but without calling Calendar.getInstance() and then throwing away the newly-created object.

like image 38
Jon Skeet Avatar answered Nov 14 '22 23:11

Jon Skeet