Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove() in ArrayList

I am writing my own Array List. Here is the remove method of the same,

public E remove(int index){
        E value =(E) elementData[index];
        for(int i=index;i<size-1;i++){
            elementData[i]=elementData[i+1];
        }
        elementData[size-1]=null;
        return value;
    }

Now i will perform some remove operation

        Box<Integer> list = new Box<>();
        for(int i=1;i<5;i++){
            list.add(i);
        }
        print(list);
        list.remove(1);
        print(list);

Now this will result in the following output,

1 2 3 4

1 3 4 null

But when i use the ArrayList from the API, i will get the output as

1234

134

Am i missing something? Can someone please explain me where i went wrong.

like image 997
Raju Mandala Avatar asked Dec 31 '13 12:12

Raju Mandala


1 Answers

I guess you need to update the size after remove() operation:

public E remove(int index){
    E value =(E) elementData[index];
    for(int i=index;i<size-1;i++){
        elementData[i]=elementData[i+1];
    }
    elementData[size-1]=null;
    --size;  // Decrement size
    return value;
}

You also need to be sure that index is in bounds of elementData array.

like image 163
Rohit Jain Avatar answered Oct 02 '22 19:10

Rohit Jain