测试 testGetBucket() 仅在密钥大于 5 个字符时不起作用。例如,如果任何小狗的名字超过 5 个字符,测试将返回 getBucket 方法的 ArrayIndexOutOfBounds 异常。
@Test
public void testGetBucket() {
List<Puppy> puppies = getPuppies();
MyHashTable<String, Puppy> instance = new MyHashTable<>(DefaultCapacity, DefaultLoadFactor);
for (int i = 0; i < 10; i++) {
Puppy puppy = puppies.get(i);
instance.put(puppy.name, puppy);
System.out.print(i);
}
List<KeyValuePair<String, Puppy>> actual = instance.getBucket(8);
assertEquals("Size of bucket is three", 3, actual.size());
for (int i = 0; i < actual.size(); i++) {
KeyValuePair<String, Puppy> p = actual.get(i);
if (p.key.equals("Bob")) {
assertEquals("Bucket contains " + p.value.name, puppies.get(1), p.value);
} else if (p.key.equals("Francois")) {
assertEquals("Bucket contains " + p.value.name, puppies.get(5), p.value);
} else if (p.key.equals("Inigo")) {
assertEquals("Bucket contains " + p.value.name, puppies.get(8), p.value);
}
}
actual = instance.getBucket(3);
assertEquals("Size of bucket is Zero", 0, actual.size());
actual = instance.getBucket(0);
assertEquals("Size of bucket is 1", 1, actual.size());
KeyValuePair<String, Puppy> p = actual.get(0);
assertEquals("Bucket contains " + p.value.name, puppies.get(2), p.value);
}
public void put(K key, V value)
{
remove(key);
KeyValuePair<K,V> element = new KeyValuePair<K,V>(key, value);
getBucket(getBucketIndex(key.hashCode())).add(element);
}
public int getBucketIndex(int hashCode)
{
return hashCode % getNumberOfCollisionBuckets();
}
public List<KeyValuePair<K,V>> getBucket(int bucketIndex)
{
return collisionBuckets[bucketIndex];
}