Returning previous value after using insertion sort in an array

98 Views Asked by At

This is somewhat of a methodology question. I am storing pairs of generics and when I store data into my array I want to only return the previous value. I am having a hard time figuring out how to return either the value in that previous location or null, if it was previously in that state.

Below you'll see what I'm trying to do.

public V put(K key, V value) {
    if (value == null) {
        throw new NullPointerException("The value you are trying to pass is null.");
    }
    if (size == table.length){
        enlarge();
    }
    int loc = 0;
    while (loc < size){
        if (table[loc].value.compareTo(value) < 0){
        loc++;
        }else{
            break;
        }
    }

    for (int index = size; index > loc; index--)
        table[index] = table[index - 1];

Here is where I am trying to actually store the old value.

    if (table[loc] != null){
        V oldValue = table[loc].value;
        table[loc] = new SVData<K, V>(key, value);
        size++;
        return oldValue;
    } else {
        table[loc] = new SVData<K, V>(key, value);
        size++;
        return null;
    }
}

The problem I am having is where in the method to actually store the old value ( I think ). Right now I have it in the if block where it checks to see whether or not that index is null, but is returning the new value. When creating method like this where is the best place in the procedure to try to store that value?

I'm also trying to move on from hack code to nice clean code so any additional advice in that arena would be great.

0

There are 0 best solutions below