Adan Vivero
Adan Vivero

Reputation: 422

How to write a remove method for hashes to remove a value?

I wrote a remove method for a HashMap and I'm getting errors that it's not returning the correct value.

The instructions read:

The remove(Object) method should remove and return the value associated with the given key if the key is found in the map. The removed entry should be replaced with the REMOVED attribute. If the map does not contain the key, this method has no effect.

Therefore, here is part of my code that is relevant to my code so it's not long code.

public class HashMap<K,V>
{
private final double MAX_LOAD_FACTOR = 0.75;
private HashEntry[] elementData;
private final HashEntry REMOVED = new HashEntry(null, null);
private int size;

public HashMap()
{
    this.elementData = new HashMap.HashEntry[10];
    size = 0;
}
public V remove(Object key)
{
    int h = hashFunction(key);
    while (elementData[h] != elementData[0] && elementData[h] != elementData[h].getKey())
    {
        h = (h + 1) % elementData.length;
    }
    if (elementData[h] == elementData[h].getKey())
    {
        elementData[h] = REMOVED;   // "removed" flag value
        size--;
        return elementData[h].getValue();
    }
    return elementData[h].getValue();
}
public class HashEntry
{
    private K key;
    private V value;

    public  HashEntry(K key, V value)
    {
        this.key = key;
        this.value = value;
    }
    public K getKey()
    {
        return key;
    }
    public V getValue()
    {
        return value;
    }
 }
}

The message I'm receiving from my error is that my size is incorrect and also, I'm returning the wrong value. Could I get help on this? I don't know where the issue occurs.

Upvotes: 0

Views: 427

Answers (1)

Adan Vivero
Adan Vivero

Reputation: 422

public V remove(Object key)
{
    int h = hashFunction(key);

    while (elementData[h] != null)
    {
        if (elementData[h].getKey() != null && elementData[h].getKey().equals(key)) // linear probing to search
        {
            V store;
            store = elementData[h].value;
            elementData[h] = REMOVED;
            size--;
            return store;
        }
        h = (h + 1) % elementData.length;
    }
    return null;
}

I almost had it, I was just suppose to return null and at the end and store the value in a different variable.

Upvotes: 1

Related Questions