I pass dates to an ArrayList
开发者_如何学Gobut when I change the Date
object, all the Date
s inside the ArrayList
will change. This is an example:
Date currentDate = new Date("6/10/2011");
ArrayList<Date> datesList = new ArrayList();
currentDate.setDate(currentDate.getDate() + 1);
datesList.add(currentDate);
currentDate.setDate(currentDate.getDate() + 1);
datesList.add(currentDate);
currentDate.setDate(currentDate.getDate() + 1);
datesList.add(currentDate);
System.out.println(datesList.toString());
This will print:
[Mon Jun 13 00:00:00 EDT 2011, Mon Jun 13 00:00:00 EDT 2011, Mon Jun 13 00:00:00 EDT 2011]
Any idea of why this happening and how could I solve it?
This is because the variable currentDate
references a single instance of Date
, which you have added to the list many times. When you call currentDate.setDate(currentDate.getDate() + 1)
you're simply updating that same object's state, and every time you call datesList.add(currentDate)
that same object is added to the ArrayList
.
Also note that setDate()
and getDate()
are deprecated methods. You should look into using a Calendar
for date manipulation:
Calendar cal = Calendar.getInstance();
cal.set(2011, 5, 10);
ArrayList<Date> datesList = new ArrayList<Date>();
datesList.add(cal.getTime());
cal.add(Calendar.DATE, 1);
datesList.add(cal.getTime());
cal.add(Calendar.DATE, 1);
datesList.add(cal.getTime());
System.out.println( datesList.toString());
or better yet, Joda Time.
You're repeatedly adding references to the same object, so you end up with a list that contains multiple references to that same object.
Try adding copies instead:
currentDate.setDate(currentDate.getDate()+1)
datesList.add(currentDate.clone()); // note the .clone()
List datesList
has the same instance in all positions. It's the same Date
instance instantiated at Date currentDate = new Date("6/10/2011");
. Try cloning it with clone()
, and modify & add each clone to the list.
ArrayList<Date> datesList = new ArrayList();
Date currentDate = new Date("6/10/2011"); ;
currentDate.setDate(currentDate.getDate()+1);
datesList.add(currentDate);
currentDate = currentDate.clone();
currentDate.setDate(currentDate.getDate()+1);
datesList.add(currentDate);
currentDate = currentDate.clone();
currentDate.setDate(currentDate.getDate()+1);
datesList.add(currentDate);
System.out.println( datesList.toString());
By doing this, each time you do currentDate = currentDate.clone()
, you're assigning a new instance of Date
with the same properties to the variable currentDate
, while not modifying the original instances already added to the list.
int dateNum = 3;
ArrayList<Date> datesList = new ArrayList();
for(int x = 0; x < dateNum; x++){
Date currentDate = new Date("6/10/2011"); //Creating a new object so your not pointing to the same one in memory
currentDate.setDate(currentDate.getDate()+1);
datesList.add(currentDate);
}
System.out.println( datesList.toString());
精彩评论