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
5f94d7a319
commit
dd5b2c30c5
@ -311,7 +311,11 @@ public class IntObjectHashMap<V> implements IntObjectMap<V>, Iterable<IntObjectM
|
|||||||
* Returns the hashed index for the given key.
|
* Returns the hashed index for the given key.
|
||||||
*/
|
*/
|
||||||
private int hashIndex(int 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
|
@Test
|
||||||
public void removeMissingValueShouldReturnNull() {
|
public void removeMissingValueShouldReturnNull() {
|
||||||
assertNull(map.remove(1));
|
assertNull(map.remove(1));
|
||||||
|
Loading…
Reference in New Issue
Block a user