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!