Tags

Silly ClassCastException in Java

Posted on by Nick. Posted in java.

Today I received a very funny ClassCastException when creating adding an object to a TreeSet. Initially I thought I had deployed the wrong code or something cose everything “looked ok”… Well it wasn’t okay.

Caused by: java.lang.ClassCastException: java.util.Locale
at java.util.TreeMap.compare(TreeMap.java:1093)
at java.util.TreeMap.put(TreeMap.java:465)
at java.util.TreeSet.add (TreeSet.java:210)

As it turns out (see above) )when you add an object to a TreeSet it gets “put” in a TreeMap. This line comes from the Java API:

public boolean add(E o) {

  return m.put(o, PRESENT)==null;

}

m is the TreeMap, o is our object that we try to add and PRESENT is just a silly dummy object. Since our object becomes the key of a Map it needs to implement Comparable. Yes, you must make sure you implement Comparable. Should I say it again?

What annoyed me the most was the exception really. ClassCastException is surely not the most meaningful of exceptions, not in my case at least. So SUN, can you please do something about this?

In the mean time, if you have similar problems just use a HashSet or implement the bloody Comparable interface…

Cheers…

Comments (1 )

  1. warxsg on January 18, 2008 - 2:08 am

    Hi,

    I got the same exception you described and I sorted it out the problem.
    Thank you very much.

    Stefano