package com.helloidea;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class ArrayListTest {
    transient Object[] elementDate;
    private static final int DEFAULT_CAPACITY = 10;
    //如果自定义容量为0,则用它来初始化ArrayList,或者用于空数组替换
    private static final Object[] EMPTY_ELEMENTDATE = {};
    //如果没有自定义容量,则用它拉初始化ArrayList,或者用于空数组对比
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATE = {};
    private int size;

    public ArrayListTest(){
        this.elementDate = DEFAULTCAPACITY_EMPTY_ELEMENTDATE;
    }

    public ArrayListTest(int ini){
        if(ini == 0){
            this.elementDate = EMPTY_ELEMENTDATE;
        }else if (ini>0){
            this.elementDate = new Object[ini];
        }else {
            System.out.println("初始容量不能小于0");
        }
    }

    public void add(Object o){
        ensureExplicitCapacity(size+1);
        elementDate[size++] = o;

    }
    //刚开始数组为空,长度为0.size = 0 minCapacity = 1
    private void ensureExplicitCapacity(int minCapacity){
        //容量不足,扩容
        if(minCapacity>elementDate.length){
            int oldCapacity = elementDate.length;
            int newCapacity = oldCapacity + (oldCapacity>>1);//这时候0扩容还是0,1扩容还是1
            if(newCapacity<minCapacity)
                newCapacity = minCapacity;
            Object []objects = new Object[newCapacity];
            //将数据复制给新数组
            System.arraycopy(elementDate,0,objects,0,elementDate.length);
            elementDate = objects;
        }
    }

    public Object get(int index){
        rangeCheck(index);
        return elementDate[index];
    }

    private void rangeCheck(int index){
        if(index>=size){
            System.out.println("下标越界");
        }
    }
    public Object remove(int index){
        rangeCheck(index);
        Object oldValue = elementDate[index];
        int numMoved = size - index - 1;
        if(numMoved>0){
            //从index+1开始,将值覆盖
            System.arraycopy(elementDate,index+1,elementDate,index,numMoved);
        }
        elementDate[--size] = null;
        return oldValue;
    }

    public boolean remove(Object o){
        for(int index = 0;index<size;index++)
            if(o.equals(elementDate[index])){
                remove(index);
                return  true;
            }
        return false;
    }
    public int size(){
        return size;
    }
}

class  test{
    public static void main(String[] args) {
        ArrayListTest list = new ArrayListTest();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);

        for (int i = 0;i<list.size();i++)
            System.out.print(list.get(i)+"  ");
    }
}
05-17 16:38