1. 程式人生 > >ArrayList底層源碼實現練習

ArrayList底層源碼實現練習

element bsp XA span exception 註意 HR -s true

/**
 * 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++; } }

ArrayList底層源碼實現練習