Here is re sizable array that will change capacity on remove and add operations (when capacity is reached). Did not test this much but looks okay.
public class ArrayBackedIndexedCollection {
private int size;
private int capacity;
private Object[] elements;
public ArrayBackedIndexedCollection(){
this.capacity = 1;
this.elements = new Object[capacity];
}
public ArrayBackedIndexedCollection(int initalCapacity){
/***************************************************
if initial capacity is less then 1 -> throw
exception
**************************************************/
this.capacity = initalCapacity;
this.elements = new Object[initalCapacity];
}
public int size(){
return size;
}
public void add(Object object){
// if capacity is reached
if ( size == capacity){
Object[] tmp = new Object[capacity];
// backup current array
System.arraycopy(elements, 0, tmp, 0, elements.length);
// re size to double capacity
elements = new Object [2*capacity];
// copy backup into re sized elements array
System.arraycopy(tmp, 0, elements, 0, tmp.length);
capacity = 2 * capacity;
}
this.elements[size] = object;
size++;
}
public Object get(int index){
return this.elements[index];
}
public void remove(int index){
elements[index] = null;
size --;
System.arraycopy(elements, index, elements, index + 1, size() - index);
}
public void insert(Object value, int position){
//...
}
}
ArrayListclass to have an idea.Arraylistbut I'd like to know how to solve the problem with abasic fixed-sized array:)ArrayList, I suggested that you look at the source code of the class to see how theremovemethod is implemented.keyor only first one?