• Post Reply Bookmark Topic Watch Topic
  • New Topic

About hashcode  RSS feed

 
Cheryl Scodario
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys, I just have a question about a method that my teacher wrote to generate hash codes for Strings. I guess there are many different ways to get hash codes. The code is the following:


So I think 256 comes from 2^8, and does that have to do with 8 bits integers/memories and two's complement? I am pretty bad with those. Can anyone explain to me in understandable terms? I don't get the "x=" part. Suppose we have a string:Hello.

 
Rob Spoor
Sheriff
Posts: 21095
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let's make the code a bit more readable by splitting up that one statement, shall we?
Now, let's take "Hello" and walk through it.

i = 0: c is the int value of "H" which is 72 (see http://www.asciitable.com/). temp1 is 72. x is 72 % modulus.
i = 1: c is the int value of "e" which is 101. Assuming modulus > 72, temp1 is (101 + 256 * 72 == 18533. x is 18533 % modulus.
etc.
 
Stephan van Hulst
Saloon Keeper
Posts: 7821
142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
x is simply the value of the hash code after processing each character. After processing the last one, the method is done and x gets returned.

On an aside, the teacher takes the size of the hash table in account. This is not really necessary, because the internals of any hash tables in Java already take care of this.
 
Rob Spoor
Sheriff
Posts: 21095
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd even say it's bad design. That hashCode() implementation will work optimally for one hash map but may work very badly for another, because it's optimized for one specific hash table size.
 
Cheryl Scodario
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob Spoor wrote:Let's make the code a bit more readable by splitting up that one statement, shall we?
Now, let's take "Hello" and walk through it.

i = 0: c is the int value of "H" which is 72 (see http://www.asciitable.com/). temp1 is 72. x is 72 % modulus.
i = 1: c is the int value of "e" which is 101. Assuming modulus > 72, temp1 is (101 + 256 * 72 == 18533. x is 18533 % modulus.
etc.


Hi Rob, thanks for rearranging the code! I hate the one-liners as well. I get the mechanism, but I was just wondering why x*256? My teacher mentioned something about binary numbers.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!