Java 向一个日历变量添加一天会影响其他日历变量

Java 向一个日历变量添加一天会影响其他日历变量,java,android,calendar,Java,Android,Calendar,我只是做以下几点: Calendar calDate = startEntryRoutine.getCalStartOfPeriod(); startentryproutine是一个已经完成的线程,现在只提供getter方法。 .getCalStartOfPeriod()返回日历变量 现在当我这样做的时候 Log.d(TAG, "createExampleList: " + startEntryRoutine.getCalStartOfPeriod().get(Calendar.DAY_OF_

我只是做以下几点:

Calendar calDate = startEntryRoutine.getCalStartOfPeriod();
startentryproutine
是一个已经完成的线程,现在只提供getter方法。
.getCalStartOfPeriod()
返回日历变量

现在当我这样做的时候

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

但是为什么呢?

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

Calendar cal2 = (Calendar) cal.clone();
然后做你的改变