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

Comparator and TreeSet

 
Henry Zhi Lin
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Ankit Garg
Sheriff
Posts: 9510
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic