File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes TreeSet - Provider Sort Method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "TreeSet - Provider Sort Method" Watch "TreeSet - Provider Sort Method" New topic
Author

TreeSet - Provider Sort Method

Lennie De Villiers
Greenhorn

Joined: Jul 17, 2009
Posts: 24
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

Joined: Jul 17, 2009
Posts: 24
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)
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18978
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: TreeSet - Provider Sort Method