ArrayList

package cn.meowrain.Datastructure.collection;

public class ArrayList<E> {
    private int size = 0;
    private int capacity = 10;
    private Object[] array = new Object[capacity];

    public void add(E element, int index) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("插入位置非法:正确范围为0~ " + size);
        }
        if (size >= capacity) {
            int newCapacity = capacity + (capacity >> 1); //扩容为原来的1.5倍
            Object[] newArray = new Object[newCapacity];
            System.arraycopy(array, 0, newArray, 0, size);
            array = newArray;
            capacity = newCapacity;
        }
        for (int i = size; i > index; i--) {
            array[i] = array[i - 1];
        }
        array[index] = element;
        size++;
    }

    public String toString() {
//        System.out.println("capacity is " + capacity);
//        System.out.println("size is " + size);
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < size; i++) {
            builder.append(array[i]).append(" ");
        }
        return builder.toString();
    }

    @SuppressWarnings("unchecked")
    public E remove(int index) {
        E element = (E) array[index];
        if (index < 0 || index > size - 1) {
            throw new IndexOutOfBoundsException("删除位置非法,删除的合法范围为: 0~" + (size - 1));
        }
        for (int i = index; i < size; i++) {
            array[i] = array[i + 1];
        }
        size--;
        return element;
    }

    @SuppressWarnings("unchecked")
    public E get(int index) {
        if (index < 0 || index > size - 1) {
            throw new IndexOutOfBoundsException("获取位置非法,只能获取0~" + (size - 1) + "的值");
        }
        return (E) array[index];
    }

    public void clear(){
        size = 0;
    }

    public int size() {
        return size;
    }

    public int getCapacity() {
        return capacity;
    }
    public boolean isEmpty(){
        if(size == 0)
            return true;
        return false;
    }
}

ArrayListRunner

package cn.meowrain.Datastructure;

import cn.meowrain.Datastructure.collection.ArrayList;

public class ArrayListRunner {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        list.add("aaa",0);
        list.add("bb",0);
        list.add("ccc",0);
        list.add("ddd",1);
        list.add("fff",2);
        System.out.println(list);
        list.remove(1);
        System.out.println(list);
        System.out.println(list.get(2));
        System.out.println(list.size());
        System.out.println(list.isEmpty());
        list.clear();
        System.out.println(list.isEmpty());
    }

}