• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

TreeSet - Provider Sort Method

 
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I read that when you use a TreeSet you need to specify which order it must sort with, if it got a natural order (like with a Byte, String, Date etc) then it will use it else you need to specify.
What happens if I don't specify a order?

cheers

Lennie
 
Lennie De Villiers
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Exception in thread "main" java.lang.ClassCastException: Student cannot be cast to java.lang.Comparable
at java.util.TreeMap.put(TreeMap.java:542)
at java.util.TreeSet.add(TreeSet.java:238)
at TreeSetExample.main(TreeSetExample.java:10)
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Lennie De Villiers wrote:Hi,

I read that when you use a TreeSet you need to specify which order it must sort with, if it got a natural order (like with a Byte, String, Date etc) then it will use it else you need to specify.
What happens if I don't specify a order?

cheers

Lennie



Basically, if you specify a comparator, it will use that, regardless of the natural sort order. If you don't then it will use the natural sort order, which means that it will use the comparable interface of the elements.

If you don't specify a comparator, and the elements are not comparable, then you will get a cast exception, when the treeset tries to access the comparable interface.

Henry
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic