Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

java.net.URL cannot be cast to java.lang.Comparable

843790Mar 5 2009 — edited Mar 5 2009
Hi

I want to store URL instances in a TreeSet, first of all because of the fast adding/removing in the middle and fast searching (.contains()). When I tried this, I got this error:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.net.URL cannot be cast to java.lang.Comparable

I thought, well, that's weird; shouldn't URL's be able to be sorted? Maybe because of differing user preferences (sorted on their url-string?, hostname?, ...), the ordering is not hard-coded but left to the coder. So, the most logical course of action I took was to make a subclass of java.net.URL and implement my own Comparable and compareTo() method.

While doing this, I found out that the java.lang.URL is a final class. I don't understand why this is, and why it prevents me from doing something as basic as sorting in a reasonably normal way. Is there a specific reason that URL is final, or may it be a bug?

I know I can solve this by using a TreeMap<String, URL>, but I just thought I'd let you know about this, as I can imagine a different scenario where there is no easy solution (eg. Arrays.sort())
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 2 2009
Added on Mar 5 2009
1 comment
436 views