我有什么:今天的日期对象。
我需要的是:将包含周的日期存储在ArrayList中。
我尝试了什么:
public static void main(String[] args) {
Date today = new Date();
Calendar cal = Calendar.getInstance();
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.setTime(today);
List<Calendar> daysOfWeek = new ArrayList<>();
IntStream
.iterate(2, n -> n+1)
.limit(7)
.forEach(n ->
{
if(n != 8){
cal.set(Calendar.DAY_OF_WEEK, n);
}else{
cal.set(Calendar.DAY_OF_WEEK, 1);
}
System.out.println("CAL_INSIDE: " + cal.getTime());
daysOfWeek.add(cal);
});
System.out.println("");
daysOfWeek.stream().forEach( cal -> System.out.println("CAL_OUTSIDE: " + cal.getTime()));
}
在forEach语句中,我得到的正是我想要的。但是ArrayList似乎只包含最后一个Date。 的输出:
CAL_INSIDE: Mon Aug 03 14:35:37 CEST 2015
CAL_INSIDE: Tue Aug 04 14:35:37 CEST 2015
CAL_INSIDE: Wed Aug 05 14:35:37 CEST 2015
CAL_INSIDE: Thu Aug 06 14:35:37 CEST 2015
CAL_INSIDE: Fri Aug 07 14:35:37 CEST 2015
CAL_INSIDE: Sat Aug 08 14:35:37 CEST 2015
CAL_INSIDE: Sun Aug 09 14:35:37 CEST 2015
CAL_OUTSIDE: Sun Aug 09 14:35:37 CEST 2015
CAL_OUTSIDE: Sun Aug 09 14:35:37 CEST 2015
CAL_OUTSIDE: Sun Aug 09 14:35:37 CEST 2015
CAL_OUTSIDE: Sun Aug 09 14:35:37 CEST 2015
CAL_OUTSIDE: Sun Aug 09 14:35:37 CEST 2015
CAL_OUTSIDE: Sun Aug 09 14:35:37 CEST 2015
CAL_OUTSIDE: Sun Aug 09 14:35:37 CEST 2015
基本上我得到了我想要的但是......
问题:为什么只有星期日存储在ArrayList中?我错过了什么?
修改
根据接受的答案输出:
CAL_INSIDE: Mon Aug 03 14:51:31 CEST 2015
CAL_INSIDE: Tue Aug 04 14:51:31 CEST 2015
CAL_INSIDE: Wed Aug 05 14:51:31 CEST 2015
CAL_INSIDE: Thu Aug 06 14:51:31 CEST 2015
CAL_INSIDE: Fri Aug 07 14:51:31 CEST 2015
CAL_INSIDE: Sat Aug 08 14:51:31 CEST 2015
CAL_INSIDE: Sun Aug 09 14:51:31 CEST 2015
CAL_OUTSIDE: Mon Aug 03 14:51:31 CEST 2015
CAL_OUTSIDE: Tue Aug 04 14:51:31 CEST 2015
CAL_OUTSIDE: Wed Aug 05 14:51:31 CEST 2015
CAL_OUTSIDE: Thu Aug 06 14:51:31 CEST 2015
CAL_OUTSIDE: Fri Aug 07 14:51:31 CEST 2015
CAL_OUTSIDE: Sat Aug 08 14:51:31 CEST 2015
CAL_OUTSIDE: Sun Aug 09 14:51:31 CEST 2015
答案 0 :(得分:3)
Calendar是一个可变对象,因此您只需存储对该对象的引用,而CAL_OUTSIDE
仅为您提供引用Calendar
对象的最后一个内部状态的7倍。
你必须搬家
Calendar cal = Calendar.getInstance();
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.setTime(today);
在循环内部获取7个不同的Calendar
个对象。