zoukankan      html  css  js  c++  java
  • java.util.ArrayList

    java.util.ArrayList

    api

    List 接口的大小可变数组的实现。实现了所有可选列表操作,并允许包括 null 在内的所有元素。

    具体介绍见 http://tool.oschina.net/uploads/apidocs/jdk-zh/java/util/ArrayList.html

    construct

    ArrayList是一个顺序列表,是对一个数组的封装

        /**
         * The array buffer into which the elements of the ArrayList are stored.
         * The capacity of the ArrayList is the length of this array buffer. Any
         * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
         * will be expanded to DEFAULT_CAPACITY when the first element is added.
         */
        transient Object[] elementData; // non-private to simplify nested class access
    
    	 /**
         * The size of the ArrayList (the number of elements it contains).
         *
         * @serial
         */
        private int size;
    

    elementData数组是存储数据的容器,size表示当前存储元素的个数

    ArrayList有三个构造函数

    • ArrayList()
      默认构造函数,lazey的思想,将elementData设置为一个空数组,在add()时初始化大小为10
    • ArrayList(int initialCapacity)将elementData初始化为固定指定大小this.elementData = new Object[initialCapacity]
    • ArrayList(Collection<? extends E> c)
      用另一个集合的底层数组来构成新的ArrayList,elementData = c.toArray();

    Collection.toArray()方法返回该集合的底层数组(ArrayList也是一个集合,实现了interface Collection)

    Collection.toArray()具体介绍
    http://tool.oschina.net/uploads/apidocs/jdk-zh/java/util/Collection.html#toArray()

    构造函数ArrayList(Collection<? extends E> c)中还有一段代码,是为了处理bug 6260652

            if ((size = elementData.length) != 0) {
                // c.toArray might (incorrectly) not return Object[] (see 6260652)
                if (elementData.getClass() != Object[].class)
                    elementData = Arrays.copyOf(elementData, size, Object[].class);
    

    因为c.toArray返回的可能不是Object[].class类型,例如返回了String[].class类型,这里用Arrays.copyOf重新复制了一下数组,并且作了类型转化

    reference http://www.zhihu.com/question/26603565

    主要方法实现

    add

        public boolean add(E e) {
            ensureCapacityInternal(size + 1);扩充容量  // Increments modCount!!
            elementData[size++] = e;//放入元素到数组
            return true;
        }
    

    get

  • 相关阅读:
    我的友情链接
    我的友情链接
    以太坊:根据例子学习Solidity
    以太坊:安装Solidity编译器
    以太坊:入门智能合约
    以太坊:Solidity手册
    Web3 :Tech Stack Overview
    Web3 – The Decentralized Web
    去中心化金融项目汇总 Defi
    跨链技术汇总
  • 原文地址:https://www.cnblogs.com/CHzero/p/5557908.html
Copyright © 2011-2022 走看看