将一天添加到一个Calendar变量会影响其他变量

时间:2019-07-16 08:04:35

标签: java android calendar

我只需执行以下操作:

Calendar calDate = startEntryRoutine.getCalStartOfPeriod();

startEntryRoutine是一个已经完成的线程,现在仅提供getter方法。 .getCalStartOfPeriod()返回Calendar变量。

现在,当我这样做时

Log.d(TAG, "createExampleList: " + startEntryRoutine.getCalStartOfPeriod().get(Calendar.DAY_OF_MONTH)+"."+startEntryRoutine.getCalStartOfPeriod().get(Calendar.MONTH)+"."+startEntryRoutine.getCalStartOfPeriod().get(Calendar.YEAR));
calDate.add(Calendar.DAY_OF_MONTH, +1);
Log.d(TAG, "createExampleList: " + calDate.get(Calendar.DAY_OF_MONTH)+"."+calDate.get(Calendar.MONTH)+"."+calDate.get(Calendar.YEAR));
Log.d(TAG, "createExampleList: " + startEntryRoutine.getCalStartOfPeriod().get(Calendar.DAY_OF_MONTH)+"."+startEntryRoutine.getCalStartOfPeriod().get(Calendar.MONTH)+"."+startEntryRoutine.getCalStartOfPeriod().get(Calendar.YEAR));

结果是:

 createExampleList: 16.6.2019
 createExampleList: 17.6.2019
 createExampleList: 17.6.2019

但是为什么?

1 个答案:

答案 0 :(得分:1)

之所以会这样,是因为Java是通过引用传递的。您需要创建日历对象的副本来解决该问题。

Calendar cal2 = (Calendar) cal.clone();

然后进行更改。