实现reHash()算法的不同方法

时间:2018-11-08 00:31:22

标签: java

我在不使用任何内置Java HashTable功能的情况下实现哈希表,并在行中出现编译时错误:

newHashTable.add(reHashValueIndex, bucket.get(j));//insert values into new table

错误:找不到适合add(int,String)的方法

我得到一个字符串与类型为String的LinkedLists的ArrayList类型不同,这就是为什么我会收到此错误,但是我可以在可能实现reHash()的另一种方法上使用一些帮助

public void reHash(ArrayList<LinkedList<String>> oldHashTable)
{
    ArrayList<LinkedList<String>> newHashTable = new ArrayList(oldHashTable.size()*2);

    //rehash values in oldHashTable
    for (int i = 0; i < (oldHashTable.size()); i++)//loop old hashTable.size number of times 
    {
        bucket = oldHashTable.get(i);//bucket = linkedList at oldHashTable
        if (bucket != null)//if hashTable linkedList bucket element contains elements 
        {
            for (int j = 0; j < bucket.size(); j++)//loop through it 
            {
                if(bucket.get(j) != null)//looking for items
                {
                    int reHashValueIndex = hash(bucket.get(j)); //rehash element 
                    newHashTable.add(reHashValueIndex, bucket.get(j));//insert values into new table at new rehashed index
                }
            }
        }
    }
    //increment expand variable by one
    expand++;
}

1 个答案:

答案 0 :(得分:1)

newHashTable的类型为ArrayList <'LinkedList <'String >>。因此,您只能添加LinkedList的对象。您可能想要做的是首先重建存储桶,然后将其添加到newHashTable中。像这样

    public void reHash(ArrayList<LinkedList<String>> oldHashTable)
    {
        ArrayList<LinkedList<String>> newHashTable = new ArrayList(oldHashTable.size()*2);

        //rehash values in oldHashTable
        for (int i = 0; i < (oldHashTable.size()); i++)//loop old hashTable.size number of times 
        {
            bucket = oldHashTable.get(i);//bucket = linkedList at oldHashTable

            if (bucket != null)//if hashTable linkedList bucket element contains elements 

            {
                newBucket = new LinkedList<String>();
                for (int j = 0; j < bucket.size(); j++)//loop through it 
                {
                    if(bucket.get(j) != null)//looking for items
                    {
                        int reHashValueIndex = hash(bucket.get(j)); //rehash element 
                        newBucket.add(reHashValueIndex, bucket.get(j));//insert values into new table at new rehashed index
                    }
                }
            }
            newHashTable.add(newBucket);
        }
        //increment expand variable by one
        expand++;
    }