Question: Pretty much the title: I'm hashing a bunch of names (10000-ish) and some are outputting as negative. (table size is 20011). 

The hash function in question is: 

```
public static long hash2 ( String key ){
  int hashVal = 0;
    for( int i = 0; i < key.length(); i++ )
      hashVal = (37 * hashVal) + key.charAt(i);
  return hashVal % 20011;
}

```

I dug around and I think I have to do something to do with "wrap around." But I don't know how to go about that.

Answer: 
This is a clear case of `Integer Overflow`. As you have mentioned in the question that the String may have upto `10000` characters then the `hashValue` will definitely overflow because it is needed to store value around `37^10000`. Even this will fail in string of length `20`.

In number theory,

```
(A+B)%M = (A%M + B%M) % M;
(A*B)%M = (A%M * B%M) % M;

```

You should apply modulo operation inside the for loop. However If you do modulo operation at last or in execution of for loop, Both will give the same answer If overflow doesn't happen.

So make changes accordingly,

```
public static long hash2 ( String key ){
  int hashVal = 0;
    for( int i = 0; i < key.length(); i++ )
    {
      hashVal = (37 * hashVal) + key.charAt(i);
      hashVal%=20011;
    }
  return hashVal;
}

```
`hashVal` is an Integer. It is most likely that your hash function is causing an Integer overflow.

You can easily resolve this by using `Math.abs()` to ensure that `hashVal` is a positive number. e.g.

```
hashVal = hashVal == Integer.MIN_VALUE ? 0 : Math.abs(hashVal);
return hashVal % 20011;

```

The mod `%` is to ensure that the final index computed is within the bounds of the table (i.e. if it's >= 20011, it uses the the remainder of division to as you say 'wrap around').