Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sets and hash code

 
Arthur Sc Chan
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As I know that, sets use hash code and equals to ensure no duplication in the set, then if I do something like override the hashCode method in an object and print hello world, then insert this object to a set, can I suppose that hello world must be shown on the console??
Something like
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15207
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Certain implementations of interface Set, such as HashSet and TreeSet, use the hash codes of objects that you put in the Set. So, such Set implementations will indeed call the hashCode() method of your class.

However, when exactly they call it, depends on how exactly HashSet and TreeSet are implemented. You would expect that "Hello World!!!" is printed in your example code, and indeed it is if you run it (did you try?). But HashSet and TreeSet don't specify anywhere when they are going to call hashCode(), so there is no guarantee that it will always be called when you put an object in the set.
 
Stephan van Hulst
Bartender
Pie
Posts: 5371
52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As far as I know, TreeSet never uses hashCode(). TreeSet is based on Comparator/Comparable.
 
Arthur Sc Chan
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You would expect that "Hello World!!!" is printed in your example code, and indeed it is if you run it (did you try?). But HashSet and TreeSet don't specify anywhere when they are going to call hashCode(), so there is no guarantee that it will always be called when you put an object in the set.

Yes. I have tried that code and seeing the Hello World in the console, but like threading, sometimes the thing I see in console may not be the only way it can be displayed, and so I just want to confirm that sentence must print out when add is called. And after my understanding on your word, it is no guarantee that hashCode method must be called when calling add method in Set implementation (say HashSet<Test>), am I correct?
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Arthur Sc Chan wrote:sometimes the thing I see in console may not be the only way it can be displayed, and so I just want to confirm that sentence must print out when add is called.

You could print a stack trace in your hashCode method and that will show you where it is called from. Replace your print statement with

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic