Allowing negative keys in IntObjectHashMap.

Motivation:

IntObjectHashMap throws an exception when using negative values for
keys.

Modifications:

Changed hashIndex() to normalize the index if the mod operation returns
a negative number.

Result:

IntObjectHashMap supports negative key values.
This commit is contained in:
nmittler 2014-10-20 08:58:38 -07:00 committed by Norman Maurer
parent 5f94d7a319
commit dd5b2c30c5
2 changed files with 13 additions and 1 deletions

View File

@ -311,7 +311,11 @@ public class IntObjectHashMap<V> implements IntObjectMap<V>, Iterable<IntObjectM
* Returns the hashed index for the given key.
*/
private int hashIndex(int key) {
return key % keys.length;
int hash = key % keys.length;
if (hash < 0) {
hash += keys.length;
}
return hash;
}
/**

View File

@ -116,6 +116,14 @@ public class IntObjectHashMapTest {
}
}
@Test
public void negativeKeyShouldSucceed() {
Value v = new Value("v");
map.put(-3, v);
assertEquals(1, map.size());
assertEquals(v, map.get(-3));
}
@Test
public void removeMissingValueShouldReturnNull() {
assertNull(map.remove(1));