问题描述
我传递日期的的ArrayList
但是当我修改日期
对象,所有的日期
ArrayList的内部> 将发生变化。这是一个例子:
I pass dates to an ArrayList
but 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());
这会打印:
[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?
推荐答案
这是因为变量的currentdate
引用日期的单个实例
,您已添加到列表中多次。当你调用 currentDate.setDate(currentDate.getDate()+ 1)
你只是更新了同一个对象的状态,并且每次调用时间 datesList 。新增(的currentdate)
相同的对象添加到的ArrayList
。
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
.
另外请注意,和的是德precated方法。你应该考虑使用日期操作:
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());
或更好,但。
这篇关于ArrayList的引用传递的日期对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!