自己实现一个泛型ArrayList

来源:互联网 发布:安卓连接mysql软件 编辑:程序博客网 时间:2024/06/05 06:16

自己实现一个ArrayList,保证最基本的 add(), remove() , get() , set() , size() ,增强for循环功能。

import java.util.Iterator;import java.util.NoSuchElementException;public class MyArrayList<E> implements Iterable<E> {    private static final int DEFAULT_CAPACITY = 10;    private int size;    private Object[] elementData;    public MyArrayList() {        clear();    }    public void clear() {        size = 0;        ensureCapacity(DEFAULT_CAPACITY);    }    public int size() {        return size;    }    public void trimToSize() {        ensureCapacity(size);    }    @SuppressWarnings("unchecked")    private E elementData(int index) {        return (E) elementData[index];    }    public E get(int index) {        if (index < 0 || index >= size)            throw new ArrayIndexOutOfBoundsException();        return elementData(index);    }    public E set(int index, E newValue) {        if (index < 0 || index >= size)            throw new ArrayIndexOutOfBoundsException();        E oldValue = elementData(index);        elementData[index] = newValue;        return oldValue;    }    public boolean isEmpty() {        return size == 0;    }    public boolean add(E e) {        add(size, e);        return true;    }    public void add(int index, E e) {        if (elementData.length == size) {            ensureCapacity(size << 1 + 1);        }        for (int i = size; i > index; i--) {            elementData[i] = elementData[i - 1];        }        elementData[index] = e;        size++;    }    public E remove(int index) {        if (index < 0 || index >= size)            return null;        E old = elementData(index);        for (int i = index; i < size - 1; i++) {            elementData[i] = elementData[i + 1];        }        size--;        return old;    }    private void ensureCapacity(int newCapacity) {        if (newCapacity < size)            return;        Object[] old = elementData;        elementData = new Object[newCapacity];        for (int i = 0; i < size; i++) {            elementData[i] = old[i];        }    }    @Override    public String toString() {        StringBuilder builder = new StringBuilder();        builder.append("[").append(elementData(0) == null ? null : elementData(0));        for (int i = 1; i < size; i++) {            builder.append(", ").append(elementData(i));        }        builder.append("]");        return builder.toString();    }    @Override    public Iterator<E> iterator() {        return new Itr();    }    private class Itr implements Iterator<E> {        private int current = 0;        @Override        public boolean hasNext() {            return current < size;        }        @Override        public E next() {            if (!hasNext())                throw new NoSuchElementException();            return elementData(current++);        }        public void remove() {            MyArrayList.this.remove(--current);        }    }}
原创粉丝点击