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:
parent
d36950503c
commit
c1217b9dd3
@ -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;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -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));
|
||||
|
Loading…
Reference in New Issue
Block a user