Win a copy of Beginning Java 17 Fundamentals: Object-Oriented Programming in Java 17 this week in the Java in General forum!
  • 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:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

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: 23912
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
 
WHAT is your favorite color? Blue, no yellow, ahhhhhhh! Tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic