Does Variable Calendar update the other when the second one is updated?

1

Hello, I've been messing with the GregorianCalendar class and I came across the following problem:

You had to go from one point in the calendar to the other, then set the first point as the second, then "reset" the second field and go back. basically the following:

GregorianCalendar gc1=new GregorianCalendar();
GregorianCalendar gc2=new GregorianCalendar();
gc1.setTime(meuTempo1);
gc2.setTime(meuTempo2);
while(!gc2.equals(variavel)){//eu tinha que voltar a gc2 até um determinado ponto
//que não necessariamente é igual a gc1.
//percorre o tempo, tirando o tanto de gc2
}
gc1=gc2;//aqui está o problema
gc2.setTime(meuTempo2);

Basically, I ran back a certain, gave a gc1=gc2 and set the gc2 again as it was before. The problem is that when I gave gc2.setTime(meuTempo2); the variable gc1 also received that parameter, that is, the attributes of gc1 also changed, as if I had placed a second line gc1.setTime(meuTempo2); .

It was easy to solve this, just replace gc1=gc2 with gc1.setTime(gc2.getTime()); but I was in doubt, if I instantiated a new variable, should not it take the attributes and then be independent of the second? If not, in what cases can this happen? And if possible, how to deal with this problem?

    
asked by anonymous 01.07.2016 / 13:59

1 answer

3

Making gc1=gc2 does not copy attribute values from gc2 to gc1 . When you do this, you are copying the reference from gc2 to gc1 . At a lower level, it means that gc1 and gc2 now point to the same memory address where the GregorianCalendar object is. Therefore, any change to the attribute that is made by gc1 and gc2 is affecting the same object.

In the case of GregorianCalendar , you can copy attribute values using the clone . Something like this:

gc1 = (GregorianCalendar)gc2.clone();

Note that the above code is assigning a new object GregorianCalendar to gc1 with the cloned values of gc2 .

    
01.07.2016 / 14:13