网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

初始化ArrayList集合的方式有几种

初始化ArrayList集合的方式有几种?可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

创新互联专注为客户提供全方位的互联网综合服务,包含不限于网站设计、做网站、莆田网络推广、微信平台小程序开发、莆田网络营销、莆田企业策划、莆田品牌公关、搜索引擎seo、人物专访、企业宣传片、企业代运营等,从售前售中售后,我们都将竭诚为您服务,您的肯定,是我们最大的嘉奖;创新互联为所有大学生创业者提供莆田建站搭建服务,24小时服务热线:13518219792,官方网址:www.cdcxhl.com

概述

ArrayList是一个以动态数组为基础实现的非线程安全的集合,ArrayList的元素可以为空、可以重复,同时又是有序的(读取和存放的顺序一致 )。

ArrayList继承AbstractList,实现了ListRandomAccess(可以快速访问)、Cloneable(可以被克隆)、java.io.Serializable(支持序列化)

ArrayList的初始化方式有三种:

1、无参构造,默认长度为10,是我们使用的最多的一种初始化方式:

/**
  * Constructs an empty list with an initial capacity of ten.
  */
  public ArrayList() {
      this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
  }

这个时候,我们从源码中可以看到,里面只有一行代码:this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA,那么定义的DEFAULTCAPACITY_EMPTY_ELEMENTDATA可以在源码中找到:

/**
  * Shared empty array instance used for default sized empty instances. We
  * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
  * first element is added.
  */
 private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

通过注释可以得知,源码中定义了一个空的数组作为默认的大小,并且在第一个元素添加进来的时候再确定把数组扩充多少,这段逻辑会在接下来添加元素部分作出解释。

2、指定初始化长度:

/**
  * Constructs an empty list with the specified initial capacity.
  * @param  initialCapacity  the initial capacity of the list
  * @throws IllegalArgumentException if the specified initial capacity
  *         is negative
  */
  public ArrayList(int initialCapacity) {
     if (initialCapacity > 0) {
         this.elementData = new Object[initialCapacity];
     } else if (initialCapacity == 0) {
         this.elementData = EMPTY_ELEMENTDATA;
     } else {
         throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
     }
  }

3、用一个Collection对象来构造

/**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public ArrayList(Collection c) {
        elementData = c.toArray();
        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);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

看完上述内容,你们对初始化ArrayList集合的方式有进一步的了解吗?如果还想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读。


网站名称:初始化ArrayList集合的方式有几种
本文链接:http://bjjierui.cn/article/jhgsho.html

其他资讯