/** * Created by chengbx on 2018/5/17. * 自己实现一个ArrayList,帮助我们更好的理解ArrayList的底层结构! * 一句话概括ArrayList的底层:数组的扩容与数据的拷贝! */ public class CbxArrayList { //存储集合中的元素 private Object[] elementData; //容器中存储的元素数量 private int size; public CbxArrayList(){ this(10); } public CbxArrayList(int initialCapacity){ if(initialCapacity < 0){ try { throw new Exception(); } catch (Exception e) { e.printStackTrace(); } } elementData = new Object[initialCapacity]; } public void add(Object obj){ //数组扩容和数据的拷贝 if(size+1 > elementData.length){ Object[] newArray = new Object[size*2+1]; System.arraycopy(elementData,0,newArray,0,elementData.length); elementData = newArray; } elementData[size++] = obj; } public int size(){ return size; } public boolean isEmpty(){ return size == 0; } public Object get(int index){ RangeCheck(index); return elementData[index]; } //索引校验 private void RangeCheck(int index){ if(index >= size){ try { throw new Exception(); } catch (Exception e) { e.printStackTrace(); } } } public void remove(int index){ int numMoved = size - index - 1; if(numMoved > 0){ System.arraycopy(elementData,index+1,elementData,index,numMoved); } elementData[--size] = null; } //遍历数组 取出与其相等(equals)的数据 删除 public boolean remove(Object o){ for(int i =0;i < size; i++){ if(o.equals(elementData[i])){ //注意:底层调用的是 而不是 == int numMoved = size - i - 1; if(numMoved > 0){ System.arraycopy(elementData,i+1,elementData,i,numMoved); } } return true; } return false; } //取出原数组索引数据 将新数据赋值到对应索引位置,返回老数据 public Object set(int index,Object o){ Object oldData = elementData[index]; elementData[index] = o; return oldData; } public void add(int index,Object object){ RangeCheck(index); System.arraycopy(elementData,index,elementData,index+1,size - index); elementData[index] = object; size++; } }