Take the 2-minute tour ×

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

share|improve this question
Have you considered just using a HashSet? –  Aurand Jan 25 '13 at 17:53

2 Answers 2

up vote 2 down vote accepted

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

if (hashNumber >= 0)
  pos = hashNumber % array.length
  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.

share|improve this answer
i see i see. my bad. sily question then. thanks! –  Alessandroempire Jan 25 '13 at 18:20
-1 this answer is just flat-out wrong. –  Louis Wasserman Jan 25 '13 at 18:51
i just tested it. and its giving me a negative integer. In other words: it does not work. –  Alessandroempire Jan 25 '13 at 19:07
Interesting... I did a quick test in Python and assumed modulo would be implemented the same elsewhere. I would expect -3 % 5 == 2. –  Andrew Clark Jan 25 '13 at 19:19
Edited my answer to work with Java. –  Andrew Clark Jan 25 '13 at 19:24


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

share|improve this answer

Your Answer


