开发者

Calendar roll affects other calendar

I have a piece of code I dont quite understand. Its causing a bug.

There's a Calendar object and a method which writes this calendar object to a string, but increments the year first. however, even though there are 2 Calendar objects, they are both being rolled.

See the method that does the roll below

public static synchronized Calendar rollDatePlus1Year(Calendar currentDate){
    Calendar rtn = currentDate;
    rtn.roll(Calendar.YEAR, 1);
    rtn.roll(Calendar.MINUTE, -1);
    return rtn;
}

from this both "currentDate" and "rtn" are incremented by a year. This 开发者_Python百科method should not change any values, but return a new represenation.

Any ideas?


Line Calendar rtn = currentDate; assigns reference to object to other variable. From this point rtn and currntDate refer to the same object. If you want, the same place in memory. Therefore all changes done using one of these references are visible using the second one because are done on the same object.


AlexR has explained why your bug is happening. To solve your issue, you need to create a new Calendar object:

public static synchronized Calendar rollDatePlus1Year(Calendar currentDate){
    Calendar rtn = Calendar.getInstance();
    rtn.setTimeInMillis(currentDate.getTimeInMillis());
    rtn.roll(Calendar.YEAR, 1);
    rtn.roll(Calendar.MINUTE, -1);
    return rtn;
}

The key thing to remember is that the assignment operator = does not create a copy of the variable to its right, it assigns to the reference on the left the reference on the right.


What you are actually doing is just copying the reference to currentDate, so any operation on rtn is on the same object as was passed in the parameter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜