ArrayList remove() implementation problem?
Hey guys I wanted to know if someone could tell me what I'm doing wrong here. I need to implement the methods of an ArrayList, and I was doing great until I had to implement the remove() method.
The problem is that the exercise tells me that after I remove an element from the list and move all the elements after the removed element one space to the left, I also need to check how many null elements there are in the array. If these null elements exceed 10, then I need to make a new array with smaller capacity and move all the elements from the previous array into the new, smaller one (for memory saving issues). Here are the exact words from my manual
My remove method works just fine in everything else except this part where I have to shrink the array.
Our approach will be as follows: the initial capacity of the internal array is fixed to
5. If a new element is to be added to the list, but that capacity has been exhausted, then the array
capacity will be increased by 5. However, the array must be shrunk whenever there are more than 10
positions available. In that case, the capacity is reduced by 5. (These numbers must be planned
carefully on a real implementation.)
What I did was to create a variable counter, and loop through the whole array. Whenever an element was null, increase the counter. Afterwards, if the counter exceeds 10, then I use a pre-made method named changeCapacity() which does the part of creating a new smaller array and moving all the elements from the previous array into this new one. But for some reason, this implementation does not seem to work. I get lots of NullPointerExceptions.
Could anyone check my code and tell me what I am doing wrong?
public E remove(int index) throws IndexOutOfBoundsException
if(index < 0 || index > this.size)
throw new IndexOutOfBoundsException("Invalid index: " + index);
E temp = this.element[index];
this.element[this.size- 1] = null;
this.moveDataOnePositionTL(index + 1 ,this.size() - 1);
int counter = 0;
for (int i = 0; i <= this.element.length - 1; i++)
if(counter >= 10)
Also, here are the moveDataOnePositionTL and changeCapacity methods:
// useful when removing an element from the list...
private void moveDataOnePositionTL(int low, int sup)
// pre: 0 < low <= sup <= (element.length - 1)
for (int pos = low; pos <= sup; pos++)
element[pos-1] = element[pos];
private void changeCapacity(int change)
int newCapacity = element.length + change;
E newElement = (E) new Object[newCapacity];
for (int i=0; i<size; i++)
newElement[i] = element[i];
element[i] = null;
element = newElement;
Re: ArrayList remove() implementation problem?
Can you make a small complete program the compiles, executes and shows the problem for testing?