抽象数据类型
首先我们需要知道的是抽象数据类型(abstract data type)简称ADT是带有一组操作的一些对象的集合。抽象数据类型是数学的抽象;诸如表、集合、图以及与它们各自的操作一起形成的对象都可以看作是ADT。
表ADT
我们把大小为0的表称为空表。
List ADT有两种流行的实现方式,一种是单链表使用ArrayList实现,另一种是双链表LinkedList。
单链表基于ArrayList类实现
ArrayList类提供了List ADT的一种可增长数组的实现。使用ArayList的优点在于对GET、SET方法的调用只花费常数的时间,但缺点也是十分明显的,在新项的INSERT和现有项的DELETE代价昂贵,除非变动时在ArrayList的末端进行。
public class MyArrayList<AnyType> implements Iterable<AnyType>{
private static final int DEFAULT_CAPACITY = 10; //设置初始容量=10
private AnyType[] theItems; //存放链表元素
private int theSize; //链表大小
public MyArrayList(){doClear();} //初始化链表
public void clear(){doClear();} //清除数据
public void doClear(){theSize=0;ensureCapacity(DEFAULT_CAPACITY);} //设置长度为0,容量初始化为10;
public int size(){return theSize;} //返回链表大小
public boolean isEmpty(){return size()==0;} //判断是否为空
public void trimToSize(){ensureCapacity(size());} //整合大小
public AnyType get(int idx){ //get方法,根据idx获取链表元素
if(idx>=size()||idx<0)
throw new ArrayIndexOutOfBoundsException();
return theItems[idx];
}
public AnyType set(int idx,AnyType newVal){ //replace
if(idx>=size()||idx<0)
throw new ArrayIndexOutOfBoundsException();
AnyType old=theItems[idx];
theItems[idx]=newVal;
return old;
}
public void ensureCapacity(int capacity){ //确保链表空间
if(capacity<theSize)
return;
AnyType[] old=theItems; //把旧的AnyType类型数组放入一个新的当中
theItems= (AnyType[]) new Object[capacity];
for(int i=0;i<size();i++)
theItems[i]=old[i];
}
public boolean add(AnyType x){ //在链表末尾添加
add(size(),x);
return true;
}
public void add(int position,AnyType x){ //在指定位置添加元素
if(position==size())
ensureCapacity(size()*2+1);
for (int i = theSize; i >position ; i--)
theItems[i]=theItems[i-1];
theItems[position]=x;
theSize++;
}
public AnyType remove(int idx){ //移除元素
AnyType removedItem=theItems[idx];
for(int i=idx;i<size()-1;i++)
theItems[i]=theItems[i+1];
theSize--;
return removedItem;
}
@Override
public Iterator<AnyType> iterator() { //生成迭代器
return new ArrayListIterator();
}
public class ArrayListIterator implements java.util.Iterator<AnyType>{
private int current=0;
@Override
public boolean hasNext() { //判断是否有下一个
return current<size();
}
@Override
public AnyType next() {
if(!hasNext())
throw new java.util.NoSuchElementException();
return theItems[current++];
}
public void remove(){
MyArrayList.this.remove(--current);}
}
}
remove方法类似于add,只是那些位于指定位置上或者指定位置后的元素向低位移动一个位置。
关于iterator方法直接返回ArrayListIterator类的一个实例,该类是一个实现iterator接口的一个类。ArrayListIterator存储当前位置的概念,并提供hasNext、next和remove方法的实现。当前位置表示要被查看的下一个元素,因此初始位置为0。