0

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

我的清单是

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()]);

4

1 回答 1

1

我猜你的错误出现在这一行:

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

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

您还试图将 a 隐式转换List<LocalDate>为 aString[]这是不可能的。当您尝试将 LocalDate 存储在字符串中时,会出现 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()]);
于 2013-07-17T22:47:24.683 回答