ArrayList的引用传递的日期对象? [英] ArrayList passing by reference with dates object?

查看:101
本文介绍了ArrayList的引用传递的日期对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我传递日期的的ArrayList 但是当我修改日期对象,所有的日期 ArrayList的内部> 将发生变化。这是一个例子:

I pass dates to an ArrayList but when I change the Date object, all the Dates 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.

另外请注意, 的setDate() 和的 GETDATE() 是德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的引用传递的日期对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆