自定义的ArrayList

来源:互联网 发布:全国电视台直播软件 编辑:程序博客网 时间:2024/05/17 02:14
//MyList接口import java.util.Collection;public interface MyList<T>{    boolean add(T t);    boolean addAll(Collection<? extends T> c);    boolean remove(T t);    Object get(int index);    boolean isEmpty();    int size();}//实现MyList接口import java.util.Arrays;import java.util.Collection;public class MyArrayList<T> implements MyList<T> {    private Object[] elementData;    private int size = 0;    public MyArrayList() {        this(10);    }    public MyArrayList(int initialCapacity) {        elementData = new Object[initialCapacity];    }    public void ensureCapacity(int minCapacity) {        int oldCapacity = elementData.length;        if (minCapacity > oldCapacity) {            int newCapacity = (minCapacity * 3) / 2 + 1;            if (minCapacity > newCapacity) {                newCapacity = minCapacity;            }            elementData = Arrays.copyOf(elementData, newCapacity);        }    }    @Override    public boolean add(T element) {        ensureCapacity(size + 1);        elementData[size++] = element;        return true;    }    @Override    public boolean addAll(Collection<? extends T> c) {        Object[] a = c.toArray();        int numNew = a.length;        ensureCapacity(size + numNew);        System.arraycopy(a, 0, elementData, size, numNew);        size += numNew;        return numNew != 0;    }    @Override    public boolean remove(T t) {        for (int i = 0; i < size; i++) {            if(t != null){                if (elementData[i].equals(t)) {                    int num = size - i - 1;                    if (num > 0) {                        System.arraycopy(elementData, i + 1, elementData, i, num);                    }                    elementData[--size] = null;                }            }else{                return false;            }        }        return true;    }    @Override    public Object get(int index) {        for (int i = 0; i < elementData.length; i++) {            if(i== index){                return elementData[index];            }        }        return null;    }    @Override    public boolean isEmpty() {        return size==0;    }    @Override    public int size() {        return size;    }}


0 0
原创粉丝点击