数据结构之重写ArrayList的底层源码

来源:互联网 发布:流程优化目的 编辑:程序博客网 时间:2024/06/06 23:19

数据结构之重写ArrayList的底层源码

  • 重写的几个主要方法
  • 构造方法
  • 添加(add)方法
  • 清除(clear)方法
  • 添加(get)以及修改(set)方法
  • 删除方法(remove)
  • 查找元素的迭代器的内部类实现(Iterator)
  • 如何合理运用这些代码,它们的时间复杂度又是多少呢?

ArrayList的实现

ArrAyList是一个java里面的一种集合,它与数组最大的区别就是能够自动增大容量并且可以进行相关的删除和添加操作。

代码块

/* * 完全纯定义一个List */public class MyArrayList<AnyType> implements Iterable<AnyType>{    //初始化集合的大小    private static final int DEFAULT_CAPACITY = 10;    private int theSize;    private AnyType[] theItem;    public MyArrayList(){        doClear();    }    public void clear(){         doClear();     }    private void doClear(){        //初始化为0        theSize = 0;        ensureCapacity(DEFAULT_CAPACITY);    }    /*     * 返回集合的大小     */    private int size(){        return theSize;    }    /*     * @true    为0     * @false   不为0     */    public boolean isEmpty(){        return size() == 0;    }    public void trimToSize(){        ensureCapacity(size());    }    private AnyType get(int idx){        if(idx < 0 || idx >= size())            throw new ArrayIndexOutOfBoundsException();        return theItem[idx];    }    public AnyType set(int idx, AnyType newVal){        if(idx < 0 || idx >= size())            throw new ArrayIndexOutOfBoundsException();        AnyType old = theItem[idx];        theItem[idx] = newVal;        return old;    }    /*     * 将新建一个数组,把旧的数组替换成新的数组     */    private void ensureCapacity(int newCapacity) {        if(newCapacity < theSize)            return;        AnyType[] old = theItem;        theItem = (AnyType[]) new Object[newCapacity];        for(int i=0; i<size(); i++)            theItem[i] = old[i];    }    public boolean add(AnyType x){        add(size(), x);        return true;    }    public void add(int idx, AnyType x){        if(theItem.length == size())            ensureCapacity(size() * 2 -1);        for(int i=theSize; i>idx; i--)            theItem[i] = theItem[i-1];        theItem[idx] = x;        theSize++;    }    public AnyType remove(int idx){        AnyType removedItem = theItem[idx];        for(int i = idx; i<size()-1; i++)            theItem[i] = theItem[i+1];  //删除的那个元素等于后面的元素        theSize--;        return removedItem;    }    @Override    public java.util.Iterator<AnyType> iterator() {        return new ArrayListIterator();    }    private class ArrayListIterator implements java.util.Iterator<AnyType>{        private int current = 0;        @Override        public boolean hasNext() {            return current < size();        }        @Override        public AnyType next() {            if(!hasNext())                throw new java.util.NoSuchElementException();            return theItem[current++];        }        public void remove(){            MyArrayList.this.remove(--current);        }    }}
0 0