不使用 putAll() 从一个 HashMap 复制到另一个

Copying from one HashMap to another without using putAll()

我试图在调整大小后将所有数据从旧的 HashMap 复制到新的。

现在,M = 10,所以当 mapSize 为 2*M 时,桶的数量将翻倍。

我得到了加倍的东西,我检查过它有效。

我只是想知道如何在不创建另一个 Hashmap 的情况下将数据从第一个 "Original" HashMap 移动到第二个。

我必须保持均匀分布,这意味着我不能只添加更多,我需要重新散列已经给出的条目。

关于如何在我的 resizeIfNeedBe() 方法中执行此操作的任何建议?

//K = type of keys
//V = type of values
public class SCHashMap<K, V> 
{
    private LinkedList<KVP<K,V>> [] buckets;
    private int mapSize;


    public SCHashMap(int M)
    {
        buckets = (LinkedList<KVP<K, V>>[]) new LinkedList[M];
        for(int i = 0; i < buckets.length; i++)
        {
            buckets[i] = new LinkedList<KVP<K, V>>();
        }
    }

    public void resizeIfNeedBe()
    {
        if (buckets.length * 2 <= mapSize) 
        {
            // need more buckets
            buckets = (LinkedList<KVP<K, V>>[]) new LinkedList[buckets.length* 2];

            //Making it so they aren't all Null
            for(int i = 0; i < buckets.length; i++)
            {
                buckets[i] = new LinkedList<KVP<K, V>>();
            }

        }

    }

    public int bucketSize(int num)
    {
        return buckets[num].size();
    }

    private int bucket(K key)
    {
        return Math.abs(key.hashCode()) % buckets.length;
    }

    public void put(K key, V value)
    {
        resizeIfNeedBe();
        int b = bucket(key);
        for(KVP<K,V> pair : buckets[b])
        {
            if(pair.getKey().equals(key))
            {
                pair.setValue(value);
                return;
            }
        }
        buckets[b].addFirst(new KVP<>(key,value));
        mapSize++;
    }

    public V get(K key)
    {
        int b = bucket(key);
        for(KVP<K,V> pair : buckets[b])
        {
            if(pair.getKey().equals(key))
            {
                return pair.getValue();
            }
        }
        return null;
    }

    public int size()
    {
        return mapSize;
    }

}

看来您需要 resizeIfNeedBe 来保留旧条目,仅此而已。我可能会这样做:

          // need more buckets
        LinkedList<KVP<K, V>> oldBuckets = buckets;
        buckets = (LinkedList<KVP<K, V>>[]) new LinkedList[buckets.length* 2];

        //Making it so they aren't all Null
        for(int i = 0; i < buckets.length; i++)
        {
            buckets[i] = new LinkedList<KVP<K, V>>();
        }

        // we know there are no duplicates so we can put things back in easily
        for (int i = 0; i < oldBuckets.length; i++) {
            for (KVP<K, V> entry : oldBuckets[i]) {
               buckets[bucket(entry.getKey())].add(entry);
            }
        }