1
Hello, I’ve been messing with the Gregoriancalendar class and I’ve come 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 walked back through a certain, given a gc1=gc2
and I again set gc2 as it was before. The problem is that when I gave the gc2.setTime(meuTempo2);
the gc1 variable also received that parameter, i.e., the attributes of gc1 also changed, as if I had placed a second line gc1.setTime(meuTempo2);
.
It was easy to fix, just replace gc1=gc2
for gc1.setTime(gc2.getTime());
but I was in doubt, if I instated a new variable, shouldn’t she take the attributes and then be independent of the second one? If not, in which cases can this happen? And if possible, how to treat this problem?
I hadn’t read the end of the question. What happens is that you are passing the object reference (memory address), not its value. Another thing, to compare dates and time, if you are using JDK8, it is recommended to use the java.time package classes, these old classes have several problems when comparing.
– user28595
Got it, but as I asked, how to get around this in other classes? using all the setters? in this case still has the
setTime
, but I have classes that have more than 30 attributes, I usesetAtributo(getAtributo())
in all?– Thomas Braz Pinto