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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With