测试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];
}
答案 0 :(得分:0)
我会在这里继续说问题就是这部分
return hashCode % getNumberOfCollisionBuckets();
如果您的命名是任何指导,则问题是hashCode。我不知道你为什么决定采用如此脆弱的实施方式。
当您的错误发生时,hashCode必须是一个值,该值会在调制后产生高于数组索引值的结果。
那么解决这个问题的方法呢?停止依赖hashCode来做一些像获取数组索引......这不是它的目的。