ansario
ansario

Reputation: 345

Implement ArrayList Class Remove Method Java

I have to implement a custom built ArrayList Class. We can't use arrayCopy. I need to be able to remove a string from the array and then move all the elements to the left by one index. My attempt is below, please help.

/****************************************************************************
 * Removes the string at the specified index from the list,
 * if it is present and shifts the remaining elements left.
 *
 * @param  str value to remove from list
 * @return the value removed from the list
 * @throws IndexOutOfBoundsException if index is invalid
 */
    public String remove(int index){
        if (index < 0 || index >= this.myArray.length)
        {
            throw new IndexOutOfBoundsException("Index out of bounds.");
        }
        else {
        String removed = this.myArray[index];
        this.myArray[index] = null;
        String [] temp = new String[this.myArray.length-1];
        for(int i = 0; i<this.myArray.length; i++){
        if (this.myArray[i] != null){
            temp[i] = this.myArray[i];
        }
    }
        return removed;
    }
    }       

I keep getting an IndexOutOfBoundsException at temp[i] = this.myArray[i].

Upvotes: 0

Views: 3513

Answers (2)

Paul Draper
Paul Draper

Reputation: 83333

The temp array is one shorter, so it can't fit everything.

You need to skip the desired index when copying the array.

The code below does this by using two different variables for the indices in the old and new arrays.

It skips incrementing one of them when the removed index is encountered.

public String remove(int index) {
    if (index < 0 || index >= this.myArray.length) {
        // FYI, this would be thrown anyway; not sure if you need to do it
        throw new IndexOutOfBoundsException("Index out of bounds.");
    }
    String removed = this.myArray[index];
    String[] temp = new String[this.myArray.length - 1];
    for(int i = 0, j = 0; i < this.myArray.length; i++){
        if (i != index) {
            temp[j++] = this.myArray[i];
        }
        // otherwise, j does not get incremented
    }
    this.myArray = temp; // don't forget this!
    return removed;
}

Upvotes: 0

yshavit
yshavit

Reputation: 43401

You're creating a temp array with one fewer elements than this.myArray. Then you iterate over all of the indexes of myArray and use those indexes to write into temp[i]. The last one is out of bounds, since temp is one smaller.

A debugger would help you find this. You could also put a System.out.println("about to access index " + i) before any line that accesses an array, and see which line prints right before the exception. Then you just need to figure out which index you're about to access (it's right there in the stdout) and think about how big the array is that you're about to access.

Upvotes: 3

Related Questions