问题
I have a list "unSortedDateList" in which dates are stored as CSV. dates are stored in following format (MM/dd/yyyy) 1/10/2012, 2/10/2011, 1/9/2011 *(note: DATES ARE STORE as COMMA SEPERATED VALUE)*
I have written a function which takes these dates from the list and sort them in ASC and store in sortedList.
TreeMap<Date, Date> sortedMap = new TreeMap<Date, Date>();
for (Date theDate : unSortedDateList)
{
sortedMap.put(theDate.getTime(), theDate);
}
List<Date> sortedList = (List<Date>) sortedMap.values();
The program is throwing a cast exception.
Can you please help me what i am doing wrong here?
回答1:
Why not sort the list with
Collections.sort(unsortedDateList)
directly?
回答2:
You are putting a long value in a date field. That has to crash.
sortedMap.put(theDate.getTime(), theDate); //getTime() is long
but your map is Date
TreeMap<Date, Date> sortedMap
回答3:
quoting the java documentation for SE6:
values() returns a Collection view of the values contained in this map.
It does not return a List: a list is a Collection but the reverse is not necessarily true.
EDIT: next time please provide a stacktrace and the exact row where the error occurs.
来源:https://stackoverflow.com/questions/8938172/cast-exception-in-sorting-date-method