• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

incorrect implementation of hashCode

 
Pavel Kubal
Ranch Hand
Posts: 360
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you show me an example of incorrect implementation of hashCode? I mean implementation which causes, that JVM is not able to locate the object in given collection.
 
Pavel Kubal
Ranch Hand
Posts: 360
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now I found one...implementation using transient attribute. Does anybody know any other?
 
Naseem Khan
Ranch Hand
Posts: 809
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This could also be one more incorrect implementation of hashCode().

hashCode() returning jst constant value like below is also not a gud implementation.



returning hashCode() value as 1 is not a very gud design becoz in this case, all the objects will land in the same bucket and in that case whole searching operation must be performed by .equals(Object) method.
In Short, Map is not efficient in searching.

Implement hashCode() in such a way that all objects land in different buckets would be a gud design in terms of efficiency of the Map.

Regards

Naseem Khan
 
Pavel Kubal
Ranch Hand
Posts: 360
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Constant is inefficient but correct.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's hard to define one that's incorrect in isolation because its correctness is tied up with the definition of equals() in the same class. This one comes pretty close to being utterly incorrect, though, in the sense that the value returned is utterly useless:

 
Pavel Kubal
Ranch Hand
Posts: 360
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, that's nice example. I wanted to know some incorrect examples, because I couldn't imagine some.

Another incorrect could be based on current time/date - but that's pretty weird idea :-)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic