Java Calendar.add affecting other Calendar objects?

arraylist, calendar, java

Solution

Calendar secondDate = startDate;
secondDate.add(Calendar.DATE, 1);

This line means that `secondDate` and `startDate` refer to the same object, so modifying one also modifies the other.

If you want a new `Calendar` instance that's one day later than the other, you'll need to clone the first instance and then modify the clone, as suggested in this answer. For instance:

Calendar secondDate = (Calendar)startDate.clone();
secondDate.add(Calendar.DATE, 1);

Problem

I am trying to add consecutive Calendar days into an `ArrayList`. When I add one day into `ArrayList` and later use Calendar.add method to go to next day, then I don't know why the `ArrayList` is also automatically modified i.e. the original entry is added 1 day? Below is my code that would explain the situation: ``` import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.ArrayList; public class TestingStuff { public static void main(String[] args) throws ParseException { ArrayList<Calendar> cals = new ArrayList<Calendar>(); SimpleDateFormat sdf = new SimpleDateFormat("MMM dd"); Calendar startDate = Calendar.getInstance(); startDate.setTime(sdf.parse("Mar 25")); cals.add(startDate); Calendar secondDate = startDate; secondDate.add(Calendar.DATE, 1); Calendar thirdDate = Calendar.getInstance(); thirdDate.setTime(sdf.parse("Mar 26")); if (cals.contains(thirdDate)) { System.out.println("It does contain"); } else { System.out.println("Sorry, it does not contain"); } } } ``` I'm not expecting 26 Mar in the `ArrayList`, but it does. Thanks a lot!

Original source

Related problems