调整HashMap的大小

时间:2017-09-30 19:19:22

标签: java hashmap collision hashcode

我创建了一个HashMap来存储条目。现在当哈希码发生冲突时,如何调整桶的大小。现在我只是将桶设置为任意素数,如果桶达到容量,我无法弄清楚如何使桶自行调整大小。

public class BucketList<K, V> extends LinkedList<Bucket<K, V>> {

    private final int NUM_BUCKETS = 997; //Arbitrary prime number 

    public BucketList() {
        initializeBuckets();
    }
    public void add(int index, BucketEntry<K, V> entry) {

        Bucket<K, V> bucket = get(index);

        if (bucket == null){
            set(index, new Bucket<>(entry));
        } else {
            BucketEntry<K, V> current = bucket.findEntry(entry.getKey());

            if (current != null) {
                current.setValue(entry.getValue());
            } else
            {
                bucket.add(entry);
            }
        }
    }

    private void initializeBuckets() {
        for (int i = 0; i < NUM_BUCKETS; i++) {
            add(null);
        }
    }
}

0 个答案:

没有答案