Collection-ArrayList

简单的实现ArrayList:
1、提供一个无参和一个有参构造函数。
2、实现size()和get()方法(不可修改)。
3、实现add(index),set(index)和remove(index)方法(可修改)。

package Collection;

import java.util.AbstractList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 *
 * @author lichunguang
 * @param 
 */
public class MyArrayList extends AbstractList implements List {
    private static Object[] DEFAULT_ELEMENTDATA = {};

    private Object[] elementData;
    private int size;

    // 两个构造函数。
    public MyArrayList() {
        this.elementData = DEFAULT_ELEMENTDATA;
    }

    public MyArrayList(Collection c) {
        this.elementData = c.toArray();
        this.size = elementData.length;
    }

    // size()方法
    @Override
    public int size() {
        return size;
    }

    // get(index)方法
    @Override
    @SuppressWarnings("unchecked")
    public E get(int index) {
        return (E) elementData[index];
    }

    // add(index, e)方法
    @Override
    public void add(int index, E e) {
        checkIndex(index);
        ensureCapacity(size + 1);
        System.arraycopy(elementData, index, elementData, index + 1, size - index);
        elementData[index] = e;
        size++;
    }

    // set(index, e)方法
    @Override
    @SuppressWarnings("unchecked")
    public E set(int index, E e) {
        checkIndex(index);
        final Object oldVal = elementData[index];
        elementData[index] = e;
        return (E) oldVal;
    }

    // remove(index)方法
    @Override
    @SuppressWarnings("unchecked")
    public E remove(int index) {
        checkIndex(index);
        final Object oldVal = elementData[index];
        System.arraycopy(elementData, index + 1, elementData, index, size - index - 1);
        elementData[--size] = null;
        return (E) oldVal;
    }

    private void ensureCapacity(int newCapacity) {
        this.elementData = Arrays.copyOf(elementData, newCapacity);

    }

    private void checkIndex(int index) {
        if (index > size || index < 0) {
            throw new IndexOutOfBoundsException();
        }

    }
}

你可能感兴趣的:(Collection-ArrayList)