Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

TreeSet - Provider Sort Method

 
Lennie De Villiers
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • 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
  • 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)
 
Henry Wong
author
Marshal
Pie
Posts: 21000
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • 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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic