底层是数组
/** * Created by yaming * 基于数组的ArrayList */ public class MyArrayList { private Object[] element; private int size; /** * 默认16 */ public MyArrayList() { //初始化默认长度16 element=new Object[16]; size=0; } /** * 初始化 自定义长度 * @param length */ public MyArrayList(int length){ element=new Object[length]; size=0; } public MyArrayList(Object[] element, int size) { this.element =element; this.size = 0; } public int size(){ return size; } public Object add(Object obj){ //1.先判断容量够不够 if(size==element.length){ Object[] oldElement=element; //默认扩容1.5倍 int newCapacity=element.length*3/2; //新的空数组 element=new Object[newCapacity]; //数据复制 System.arraycopy(oldElement,0,element,0,oldElement.length); } element[size++]=obj; return true; } public Object get(int index){ return element[index]; } public Object remove(int index){ Object obj=get(index); for(int i=index;i<size-1;i++){ element[index]=element[index+1]; } size--; return obj; } public void clearAll(){ element=new Object[16]; size=0; } }