Cast Exception in sorting date method

假如想象 提交于 2020-01-06 15:41:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!