0

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?

Namita
  • 779
  • 4
  • 12
  • 24

3 Answers3

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
juergen d
  • 201,996
  • 37
  • 293
  • 362
  • Correct, I have changed it to theDate. Still its throwing an exception. – Namita Jan 20 '12 at 07:48
  • why does people upvote this when it is obviously not the key point of the question? – STT LCU Jan 20 '12 at 08:09
  • @STT LCU Its not about scoring point. Its about identifying problems ( even not asked) in the code. – Namita Jan 20 '12 at 09:15
  • i haven't even mentioned points, it's just that this answer isn't related to the question, even if it is correct indeed in its own scope. – STT LCU Jan 20 '12 at 10:02
2

Why not sort the list with

Collections.sort(unsortedDateList) 

directly?

Peter Svensson
  • 6,105
  • 1
  • 31
  • 31
1

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.

STT LCU
  • 4,348
  • 4
  • 29
  • 47