Intro to Data Structures; Array Implementation of List
Introduction to Data Structures; an Array Implementation of List
Data Structures
Much of programming involves the storage and retrieval of data. Many of the most efficient algorithms for important problems are based on the use of specific data structures; the efficiency of the algorithm depends on the efficiency of the underlying data structure. Software design often involves the choice of appropriate data structures. So the study of data structures is considered by computer scientists to be fundamental to learning computer science.Data structures are used for:
- Temporary storage for specific algorithms and programs. For example, stacks and trees are used heavily by compilers, operating systems use queues for scheduling processes.
- Long term storage for databases.
- Efficiency (of time and space)
- Applicability (useful in a variety of problems)
- Reusability (Get the interface right!)
- Designing specifications for abstract data types, such as List, Set, Map, Stack, Queue, etc.
- Writing concrete implementations of ADTs.
- Learning the common applications of various ADTs.
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 int capacity;
private Object[] data;
OurList(){
nitems = 0;
capacity = 10;
data = new Object[10];
}
OurList(int capacity){
nitems = 0;
this.capacity = capacity;
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];
capacity = 2*capacity;
}
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 >= capacity)
resize();
data[nitems] = obj;
++nitems;
return true;
}
public void add ( int index, Object obj){
if(index<0 || index>nitems)
throw new IndexOutOfBoundsException();
if(nitems >= capacity)
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;
}