学习数据结构时看了java集合中的ArrayList的实现,照着书上写了一遍,并添加了个人理解的注释
一起学习,卷啊~卷啊~
package Arraytest;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.function.Consumer;
public class MyArraylist<AnyType> implements Iterable<AnyType> {
private static final int DEFAULT_CAPACITY=10; //默认数组长度
private int theSize; //数组当前的长度
private static AnyType[] theIntems; //任何类型的数组 真实的ArrayList的实现是Object[]
public MyArraylist(){
doCrear(); //创建实例需要进行初始化操作
}
public void clear(){ //清零
doCrear();
}
public void doCrear(){ //做一个初始化的操作
theSize=0;
ensureCapacity(DEFAULT_CAPACITY);
}
public static int size(){ //该方法的特点?
return theSize;
}
public boolean isEmpty(){ //该方法是为了判断集合是否为空
if (theSize>0){
return false;
}else {
return true;
}
}
public AnyType get(int index){ //通过index来获取值
if (index<0||index>size()) //判断索引是否小于0或大于当前数组的最大值,抛出异常
throw new ArrayIndexOutOfBoundsException();
return theIntems[index];
}
public AnyType set(int index,AnyType m){ //替换原数组这种的某个元素,返回被替换的元素
if (index<0||index>size()) //判断索引是否小于0或大于当前数组的最大值,抛出异常
throw new ArrayIndexOutOfBoundsException();
AnyType old=theIntems[index];
theIntems[index]=m;
return old;
}
//该方法用于从老数组当中的内容拷贝到新数组
public void ensureCapacity(int newCapacity){
if (newCapacity<theSize){ //判断现在数组的长度是否大于原来数组原来长度,小于就不做处理
return;
}
AnyType old[]=theIntems; //将老数组赋值给old
theIntems=(AnyType[]) new Object[newCapacity]; //创建新数组
for (int i = 0; i < size(); i++) {
theIntems[i]=old[i];
}
}
public boolean add(AnyType x){ //add的第一种方法
add(size(),x);
return true;
}
public void add(int index,AnyType x){ //add的第二种方法
if (index==size()) //当index等于数组长度时需要扩容2倍(+1用于大小为0的情况)
ensureCapacity(size()*2+1);
for (int i=theSize;i>index;i++) //将index后面的元素向后推一位
theIntems[i]=theIntems[i-1];
theIntems[index]=x; //将index的位置存放x
theSize++;
}
public AnyType remove(int index){ //根据下标删除某个元素,返回删除的元素
AnyType removeItem=theIntems[index];
for (int i=index;i<size();i++) //将index后面的元素向前推一位
theIntems[i]=theIntems[i+1];
return removeItem;
}
public java.util.Iterator<AnyType> iterator(){
return new ArraylistIterator(this);
}
private static class ArraylistIterator implements Iterator<AnyType>{ //内部类实现迭代器
private int current=0;
private MyArrayList<AnyType> theList;
public ArraylistIterator(MyArrayList<AnyType> list){
thelist=list;
}
@Override
public boolean hasNext() {
return current<size();
}
@Override
public AnyType next() {
if (!hasNext())
throw new NoSuchElementException();
return theIntems[current++];
}
@Override
public void remove() {
MyArraylist.this.remove(--current);
}
}
}