File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Comparator and TreeSet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Comparator and TreeSet" Watch "Comparator and TreeSet" New topic

Comparator and TreeSet

Henry Zhi Lin
Ranch Hand

Joined: Nov 04, 2008
Posts: 69
Hi, guys

The following code is Devaka's Exam Lab practice1 question 55.

WHy this have an runtime exception, I thought the treeset has a comparator to compare the value that saved into the set?

Can anyone explain to me how does this work?

SCJP 5.0
Ankit Garg

Joined: Aug 03, 2008
Posts: 9453

For inserting a class' element to a TreeSet, it must implement Comparable interface and override the compareTo method. This code is implementing Comparator interface and overriding compare method. Comparator is used when we want to use an external sorting logic which is different from the one in the class whose objects are being added to the TreeSet...

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
I agree. Here's the link:
subject: Comparator and TreeSet
It's not a secret anymore!