• ArrayList源码解析


    放假,倍感无聊。兴起,观ArrayList源码,感之,故而记之。

       整体的类结构图。在《thingking in java》第四版,17章可依完整的看到容器类的整体结构图。单看ArrayList的结构,看到一个完整的结构图。

    Iterator > Collection >List >AbstractList >ArrayList 。

    1,Iterable接口,javadoc对该类的解释比较简单,Implementing this interface allows an object to be the target of    the "foreach" statement.可以简单的来看出,实现当前接口的类都可以使用foreach循环遍历。

    2,Collection接口继承了Iterable接口。同时声明了一个集合类必须的一些成员变量和方法。

    3,List<E> 接口继承Collection接口,增加了对于链表需要的方法和变量。

    通过阅读List的javadoc文档,可以看出一些几点:

    1. Unlike sets, lists typically allow duplicate elements.
    2. they typically allow multiple  null elements if they allow null elements at all.
    3. The <tt>List</tt> interface provides a special iterator, called a <tt>ListIterator</tt>
    4,AbstractList extends AbstractCollection<E> implements List<E> 。

    5,ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable。

    6,ArrayList的初始化默认长度为10, 

    private static final int DEFAULT_CAPACITY = 10;

    当然在代码中我们可以指定长度,ArrayList(int initialCapacit)。

    7,ArrayList的add方法。

    在平时的使用中,基本上都是调用一个add方法就行了,实际中,add方法在后台经历了好几种。下面可以来看看:

    1) public boolean add(E e):在该方法内部,首先调用 ensureCapacityInternal(size + 1); 

    2)private void ensureCapacityInternal(int minCapacity):在ensureCapacityInternal方法内部,首先判断

     if (elementData == EMPTY_ELEMENTDATA) {
                minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
            }

    是不是当前对象维护的elementData是一个空数组,如果是的话,获取传入值和默认长度中的大数。

    调用 ensureExplicitCapacity(minCapacity);

    3)在 private void ensureExplicitCapacity(int minCapacity) 方法中, modCount++;(尚未看懂这个方法的作用)。

    if (minCapacity - elementData.length > 0)
                grow(minCapacity);判断传入值和当前维护数组的大小,如果大于当前维护数组。

    4) private void grow(int minCapacity) {
            // overflow-conscious code
            int oldCapacity = elementData.length;
            int newCapacity = oldCapacity + (oldCapacity >> 1);
            if (newCapacity - minCapacity < 0)
                newCapacity = minCapacity;   增加当前数组长度的一半长度。
            if (newCapacity - MAX_ARRAY_SIZE > 0)
                newCapacity = hugeCapacity(minCapacity);
            // minCapacity is usually close to size, so this is a win:
            elementData = Arrays.copyOf(elementData, newCapacity);
        }

    5)增加

      elementData[size++] = e;
            return true;



    欢迎转载,但转载请注明原文链接[博客园: http://www.cnblogs.com/jingLongJun/]
    [CSDN博客:http://blog.csdn.net/mergades]。
    如相关博文涉及到版权问题,请联系本人。
  • 相关阅读:
    oracle中查询表是否存在
    asp.net webform/mvc导出Excel通用代码
    分享给大家一个500G.Net ftp资料库
    C# 使用TopShelf实现Windows服务部署
    C#基于Quartz.NET实现任务调度并部署Windows服务
    附加进程找不到w3wp.exe进程解决方案
    在vs2015中使用附加进程的方式调试IIS中的页面
    删除datatable的行后,出现“不能通过已删除的行访问该行的信息”的错误,即DeletedRowInaccessibleException
    C# FTP操作类
    C# vb .net实现发光效果
  • 原文地址:https://www.cnblogs.com/jingLongJun/p/4491084.html
Copyright © 2020-2023  润新知