import java.util.Arrays;
public class ArrayList<T> {
private int DEFAULT_SIZE = 16;
//保存数组长度
private int capacity;
//保存顺序线性表的元素
private Object[] elementData;
//保存线性表当前元素的个数
private int size = 0;
//创建默认空顺序线性表
public ArrayList(){
capacity = DEFAULT_SIZE;
elementData = new Object[capacity];
}
//以一个初始化元素创建顺序线性表
public ArrayList(T element){
this();
elementData[0] = element;
size++;
}
/**
* 以指定长度的数组来创建顺序线性表
* @param element 顺序线性表中的第一个元素
* @param initSize 指定顺序线性表底层数组的长度
*/
public ArrayList(T element, int initSize){
capacity = 1;
//把capacity设置为大于intiSize的最小的2的n次方
while(capacity < initSize){
capacity <<= 1;
}
elementData = new Object[capacity];
elementData[0] = element;
size++;
}
//获得线性表的大小
public int length(){
return size;
}
//获得线性表中索引为i的元素
public T get(int i){
if(i < 0 || i>size -1){
throw new IndexOutOfBoundsException("线性表索引越界");
}
return (T)elementData[i];
}
//查找顺序线性表中指定元素的索引
public int locate(T elememt){
for(int i = 0; i < size ; i++){
if(elementData[i].equals(elememt)){
return i;
}
}
return -1;
}
//向顺序线性表的指定位置插入一个元素
public void insert(T element, int index){
if(index<0 || index>size){
throw new IndexOutOfBoundsException("线性表索引越界");
}
ensureCapacity(size+1);
//插入索引之处后的所有元素向后移动一格
System.arraycopy(elementData, index, elementData, index+1, size-index);
elementData[index] = element;
size++;
}
//在线性表的开始处添加一个元素
public void add(T element){
insert(element,size);
}
private void ensureCapacity(int minCapacity) {
//如果数组原长度小于所需长度
if(minCapacity > capacity){
while(capacity<minCapacity){
capacity <<= 1;
}
elementData = Arrays.copyOf(elementData, capacity);
}
}
//删除线性表中指定索引处的元素
public T delete(int index){
if(index<0 || index>size-1){
throw new IndexOutOfBoundsException("线性表索引越界");
}
T oldValue = (T)elementData[index];
int numMoved = size - index - 1;
if(numMoved > 0){
System.arraycopy(elementData, index+1, elementData, index, numMoved);
}
elementData[--size] = null;
return oldValue;
}
//删除线性表的最后一个元素
public T remove(){
return delete(size-1);
}
//判断顺序线性表是否为空
public boolean empty(){
return size == 0;
}
//清空线性表
public void clear(){
Arrays.fill(elementData, null);
size = 0;
}
public String toString(){
if(size == 0){
return "[]";
} else {
StringBuilder sb = new StringBuilder("{");
for(int i=0;i<size;i++){
sb.append(elementData[i].toString()+",");
}
int len = sb.length();
return sb.delete(len-1, len).append("}").toString();
}
}
}
这其实就是一个ArrayList的简单功能版