Reputation: 23
I am trying to figure out how does that method works, because i would like to make my own. So I came to this point:
public static deleteMe(int index){
for(int i=0;i<arrayList.size;i++){
if(i==index){
// how to tell java to delete that member of list on the index i,
// but not to be arrayList.remove()
}
}
}
Upvotes: 0
Views: 3493
Reputation: 5566
ArrayList is based internally on a simple array, so when you delete by index you simply move everything that has higher index than the removed element one place down, look at te JDK implementation:
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
Ofcourse the inner array (elementData) is package-access so you don't have access to it, that's the whole point. If you are implementing your own list I suggest extending the AbstractList
. If you are not then this question doesn't make sense, like I said, that's the whole point of ArrayList
to encapsulate the inner array so you can operate on it only through methods available to you.
If you want to delete not by index, but by passing some instance of type that the ArrayList
is holding, that requires the equals
check, so that type needs to properly override equals
and hashCode
methods.
Upvotes: 2