Java容器_List接口_ArrayList类

来源:互联网 发布:unity3d音乐播放器 编辑:程序博客网 时间:2024/06/04 15:53

List接口,打开源码看看:

public interface List<E> extends Collection<E> {    // Query Operations    /**     * Returns the number of elements in this list.  If this list contains     * more than <tt>Integer.MAX_VALUE</tt> elements, returns     * <tt>Integer.MAX_VALUE</tt>.     *     * @return the number of elements in this list     */    int size();
通过代码,我们可以看出List接口继承了Collection接口,所有拥有Collection的所有方法,另外,又新定义了一些方法,例如get(i),set(int,E)等List列表操作的方法。

ArrayList类,打开源码看看:

public class ArrayList<E> extends AbstractList<E>        implements List<E>, RandomAccess, Cloneable, java.io.Serializable{    /**     * The array buffer into which the elements of the ArrayList are stored.     * The capacity of the ArrayList is the length of this array buffer.     */    private transient Object[] elementData;    /**     * The size of the ArrayList (the number of elements it contains).     *     * @serial     */    private int size;    /**     * 默认长度是10.     */    public ArrayList() {        this(10);    }

通过代码,我们可以知道,ArrayList实现了List接口;
Object[] elementData,说明ArrayList是通过数组实现的;
Resizable-array implementation of the List interface.
类的描述文字也清楚的说明了该类就是一个可变数组,上文我们分析过了StringBuilder;
那ArrayList的实现和StringBuilder是一样,就是存储的是对象罢了。
看代码:
   /**     * Appends the specified element to the end of this list.     *     * @param e element to be appended to this list     * @return <tt>true</tt> (as specified by {@link Collection#add})     */    public boolean add(E e) {        ensureCapacityInternal(size + 1);  // Increments modCount!!        elementData[size++] = e;        return true;    }
连扩容的函数名都一样,不说了。

0 0
原创粉丝点击