将LocalDate列表保存到数组[] []

时间:2013-07-17 22:39:09

标签: java arrays list

我想将列表中的日期保存到数组[] []?

我的清单是

List<LocalDate> dates = getWeekendDates
        (new LocalDate(year, month, (day+2)), new LocalDate((year+1), nymonth ,nyday));

private static List<LocalDate> getWeekendDates
    (LocalDate start, LocalDate end)
{
    List<LocalDate> result = new ArrayList<LocalDate>();
    for (LocalDate date = start;
         date.isBefore(end);
         date = date.plusDays(1))
    {
        int day = date.getDayOfWeek();
        // These could be passed in...
        if (day == DateTimeConstants.SUNDAY)
        {
            result.add(date);
        }
    }
    return result;
}   

我用过:

String[] SundayArray = dates.toArray(new String[dates.size()]);
System.out.println(SundayArray[5]);

这是错误输出:

Exception in thread "main" java.lang.ArrayStoreException 
    at java.lang.System.arraycopy(Native Method) 
    at java.util.ArrayList.toArray(Unknown Source) 
    at Test.main(Test.java:27)

第27行是String[] SundayArray = dates.toArray(new String[dates.size()]);

1 个答案:

答案 0 :(得分:1)

我猜你的错误来自这条线:

String[][] SundayArray = dates.toArray(new String[dates.size()]);

您为该方法提供了一维数组(new String[dates.size()])并尝试将其设为二维数组(String[][] SundayArray)。

您还试图将List<LocalDate>隐式转换为String[]这是不可能的。当您尝试将LocalDate存储在String中时,会出现ArrayStoreException。你需要更多的东西:

List<String> temp = new ArrayList(dates.size());
for (LocalDate date : dates) {
    temp.add(date.toString()); //toString() or the appropriate method
}
String[] SundayArray = temp.toArray(new String[dates.size()]);