java中arraylist的底层实现

作者: 这是朕的江山 | 来源:发表于2016-07-23 19:54 被阅读927次

    参考:
    java集合--arraylist的实现原理

    详细的请参考上文,以下是我的简单总结:
    1.arraylist不是线程安全的,只能用在单线程环境下

    2.arraylist支持序列化和克隆

    3.arraylist只有两个私有属性,如下,由此可以看出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. 
          */  
         private transient Object[] elementData;  
       
         /** 
          * The size of the ArrayList (the number of elements it contains). 
          * 
          * @serial 
          */  
         private int size;
    

    4.arraylist一共有三种构造方法,如下

    // ArrayList带容量大小的构造函数。    
        public ArrayList(int initialCapacity) {    
            super();    
            if (initialCapacity < 0)    
                throw new IllegalArgumentException("Illegal Capacity: "+    
                                                   initialCapacity);    
            // 新建一个数组    
            this.elementData = new Object[initialCapacity];    
        }    
       
        // ArrayList无参构造函数。默认容量是10。    
        public ArrayList() {    
            this(10);    
        }    
       
        // 创建一个包含collection的ArrayList    
        public ArrayList(Collection<? extends E> c) {    
            elementData = c.toArray();    
            size = elementData.length;    
            if (elementData.getClass() != Object[].class)    
                elementData = Arrays.copyOf(elementData, size, Object[].class);    
        }
    

    当调用无参构造方法时,会初始化容量为10;当参数为一个int类型的容量时,arraylist的初始化为指定容量;当参数为一个集合类型时,arraylist的大小初始化为集合的大小

    5.调用add方法时,会使用ensureCapacity(int capacity)方法先检测当前容量是否满足所要增加的元素的个数,如果不足则会对arraylist进行扩容,扩容至原容量的1.5倍+1,如果还不足,则会直接扩容至ensureCapcity方法中的capacity值的容量。

    6.在arraylist中间插入一组数据时,在检查容量和扩容之后,会将原本从插入位置index位置到最后的数据都拷贝到新扩容的空间,然后再把要插入的数据插入到原来数据腾出的位置

    7.在arraylist中删除数据时,会把后面的数据往前复制,保证中间没有无效的数据,然后对原本往前挪的位置设置为null

    相关文章

      网友评论

        本文标题:java中arraylist的底层实现

        本文链接:https://www.haomeiwen.com/subject/hwtwjttx.html