• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Using a Comparator for the TreeSet class

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,

When a Comparator object is used in a TreeSet class, why is it that the add() method in TreeSet class does not add any elements if the compare() method in the Comparator class returns 0 for those two elements?

Thanks,


Mack
 
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
"Set" means no duplication.
Comparator.compareTo() returning "0" means two "identical" objects.
 
Guangcheng Zhou
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, so is compareTo() method used in adding elements? I thought only hashCode() and equals() were used.
 
James Quinton
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Guangcheng Zhou:
Yes, so is compareTo() method used in adding elements? I thought only hashCode() and equals() were used.



It uses either natural order if the Comparator is not provided, or an order specified by Comparator.compareTo() method.
It has nothing to do with Object's hashCode() or equals() methods.
However, the elements must be mutually comparable.
 
Guangcheng Zhou
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think hashCode() is used for HashSet though.
 
James Quinton
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Guangcheng Zhou:
I think hashCode() is used for HashSet though.



hashCode() is considered as an Object's ID. hashCode() IS used by HashSet and HashMap, as name suggested. TreeSet is noting using hashCode()
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic