An Array Implementation of List
An Array Implementation of List
Implementing List with an array
One way to implement a list is to use an array of Objects.class OurList implements List {
private int nitems;
private Object[] data;
OurList(){
nitems = 0;
data = new Object[10];
}
OurList(int capacity){
nitems = 0;
data = new Object[capacity];
}
private void resize(){
Object[] temp = data;
data = new Object[2 * temp.length];
for(int k = 0; k < temp.length; k++)
data[k] = temp[k];
}
public int size(){
return nitems;
}
public void clear(){
this();
}
public boolean isEmpty(){
return nitems==0;
}
public Object get(int index){
if(index<0 || index>=nitems)
throw new ArrayOutOfBoundsException();
return data[index];
}
public Object set(int index, Object obj){
if(index<0 || index>=nitems)
throw new ArrayOutOfBoundsException();
Object returnObject = data[index];
data[index] = obj;
return returnObject;
}
public boolean add(Object obj){
if(nitems >= data.length)
resize();
data[nitems] = obj;
++nitems;
return true;
}
public void add ( int index, Object obj){
if(index<0 || index>nitems)
throw new IndexOutOfBoundsException();
if(nitems >= data.length)
resize();
for(int k=nitems; k>index; k--)
data[k] = data[k-1];
data[index] = obj;
++nitems;
}
public Object remove (int index){
if(index<0 || index>=nitems)
throw new IndexOutOfBoundsException();
Object returnObject = data[index];
for(int i = index; i < (nitems-1); i++)
data[i] = data[i+1];
--nitems;
return returnObject;
}
public boolean equals(Object obj){
boolean result;
if(getClass() != obj.getClass())
result = false;
else {
OurList other = (OurList) obj;
if(nitems != other.nitems)
result = false;
else {
result = true;
for(k=0; k<nitems; k++)
if(data[k] != other.data[k])
result = false;
}
}
return result;
}
public Iterator iterator(){
return new Iterator(){
int currentIndex = 0;
public boolean hasNext(){
return currentIndex < nitems;
}
public Object next(){
return data[currentIndex++];
}
};
}
}