1

Basically i am using the hasCode() from the Objects class to obtain a hash code of some strings.

I want that number to represent a position in the array. Basically a hash table. I havent written code for this yet.

I had in mind:

 int hashNumber = SomeString.hascode(), pos; 
 String array[] = new String[10];

 if (hashNumber > 0)
   pos = hashNumber % array.length
 if (hasNumber < 0 )
   //dont know what to do

I do know for a fact that hashCode can return a negative integer. What to do if its negative integer? i though about adding the array length

  pos = hashNumber + array.length

is this the best way?

thanks in advance

1
  • Have you considered just using a HashSet? Commented Jan 25, 2013 at 17:53

2 Answers 2

3

If hashNumber is negative, just get the mod of -hashNumber (which will be positive):

if (hashNumber >= 0)
  pos = hashNumber % array.length
else
  pos = -hashNumber % array.length

Or for a single expression that will work for both:

pos = (hashNumber % array.length + array.length) % array.length

See this answer to a question about Java's behavior with mod and negative numbers.

Sign up to request clarification or add additional context in comments.

7 Comments

i just tested it. and its giving me a negative integer. In other words: it does not work.
Interesting... I did a quick test in Python and assumed modulo would be implemented the same elsewhere. I would expect -3 % 5 == 2.
question: why do you do: %array.length outside the parenthesis? with: (hashNumber % array.length + array.length) it will give you a number between the array length. It seems redundant to me.
Consider (9 % 10 + 10), that would become 9 + 10 or 19, so we need the % 10 on the outside to bring it back in range. It is only for negative numbers where the value inside of the parentheses will be in the right range.
o yes yes. Well i decided to make an IF, and when its a negative integer: it will calculate the position using: (hashNumber % array.length + array.length) and for what i seen its valid.
|
0

http://docs.oracle.com/javase/specs/jls/se5.0/html/expressions.html#15.17.3

the sign of the result equals the sign of the dividend.

See here for more discussion: How does java do modulus calculations with negative numbers?

To be safe, you could simply use pos = Math.abs(hashNumber) % array.length

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.