*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes incorrect implementation of hashCode Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "incorrect implementation of hashCode" Watch "incorrect implementation of hashCode" New topic
Author

incorrect implementation of hashCode

Pavel Kubal
Ranch Hand

Joined: Mar 13, 2004
Posts: 356
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

Joined: Mar 13, 2004
Posts: 356
Now I found one...implementation using transient attribute. Does anybody know any other?
Naseem Khan
Ranch Hand

Joined: Apr 25, 2005
Posts: 809
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


Asking Smart Questions FAQ - How To Put Your Code In Code Tags
Pavel Kubal
Ranch Hand

Joined: Mar 13, 2004
Posts: 356
Constant is inefficient but correct.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

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:



[Jess in Action][AskingGoodQuestions]
Pavel Kubal
Ranch Hand

Joined: Mar 13, 2004
Posts: 356
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 :-)
 
Don't get me started about those stupid light bulbs.
 
subject: incorrect implementation of hashCode