在不使用putAll()的情况下从一个HashMap复制到另一个HashMap

时间:2016-02-16 19:02:53

标签: java hashmap linkedhashmap

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

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

我得到了双倍的东西,它确实有效。

我只是想知道如何从第一个"原始" HashMap到第二个而不创建另一个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;
    }

}

1 个答案:

答案 0 :(得分:1)

看起来您需要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);
            }
        }
相关问题