Different way of implementing my reHash() algorithm

I'm implementing a hash table without the use of any built-in java HashTable features, and getting a compile-time error with the line:

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

ERROR: no suitable method found for add(int, String)

I get that a String is not the same type as an ArrayList of LinkedLists of type String, which is why I'm getting the error, but I could use some assistance as to another way to possibly implement 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 answer

  • answered 2018-11-08 00:45 Justin

    newHashTable is of type ArrayList <'LinkedList<'String>>. so you can only add objects that are LinkedList. What you probably want to do is first rebuild your bucket, and then add it to your newHashTable. something like this

        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++;
        }