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 46b02a5818
commit f9706fda42
2 changed files with 13 additions and 1 deletions

View File

@ -312,7 +312,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));