0

测试 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];
    }
4

1 回答 1

0

我要在这里勉强说问题出在这部分

return hashCode % getNumberOfCollisionBuckets();

如果您的命名是任何指导,那么问题就是 hashCode。我不知道您为什么决定采用如此脆弱的实现。

当您的错误发生时,hashCode 的值必须在调制后给出高于数组索引值的结果。

那么解决这个问题的方法是什么?停止依赖 hashCode 来做一些事情,比如获取数组索引......这不是它的目的。

于 2013-05-06T01:18:34.640 回答