Java集合框架-ArrayList

1,ArrayList介绍

  1. ArrayList简介
    1,ArrayList是一个数组队列,相当于动态数组可以实现动态扩容。它继承了 AbstractList,实现List, RandomAccess, Cloneable, java.io.Serializable四个接口。
    2,ArrayList继承了AbstractList实现List接口,他是一个数组,提供了相应的增删改查遍历等功能。
    3,ArrayList 实现了RandmoAccess接口,即提供了随机访问功能。
    4,ArrayList 实现了Cloneable接口,即覆盖了函数clone(),能被克隆。
    5,ArrayList 实现java.io.Serializable接口,这意味着ArrayList支持序列化,能通过序列化去传输。

  2. ArrayList的构造函数

 public ArrayList(int initialCapacity) {//有参构造,指定初始容量
 public ArrayList() {//无参构造,默认初始容量
 public ArrayList(Collection<? extends E> c) {//有参构造,通过集合构造新的集合

2,ArrayList底层数据结构

ArrayList和collection关系图

在这里插入图片描述
ArrayList包含了两个重要的对象:elementData 和 size。
(01) elementData 是"Object[]类型的数组",它保存了添加到ArrayList中的元素。实际上,elementData是个动态数组,我们能通过构造函数 ArrayList(int initialCapacity)来执行它的初始容量为initialCapacity;如果通过不含参数的构造函数ArrayList()来创建ArrayList,则elementData的容量默认是10。elementData数组的大小会根据ArrayList容量的增长而动态的增长,具体的增长方式,请参考源码分析中的 grow函数。

private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);//1.5倍扩容
        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);
    }


(02) size 则是动态数组的实际大小。

3,JDK源码解读

研究1.8的源码可以总结得出

  1. ArrayList 实际上是通过一个数组去保存数据的。当我们构造ArrayList时;若使用默认构造函数,则ArrayList的默认容量大小是10。
  2. 当ArrayList容量不足以容纳全部元素时,ArrayList会重新设置容量:新的容量= oldCapacity + (oldCapacity >> 1);//1.5倍扩容
  3. ArrayList的克隆函数,即是将全部元素克隆到一个数组中。

4,ArrayList的三种遍历方式

1,迭代器遍历即通过Interator遍历

Integer val = null;
Iterator iterator = arrayList.iterator;
while(iterator.hasnext){
val = iterator.next;
}

2,第二种,随机访问,通过索引值去遍历。
由于ArrayList实现了RandomAccess接口,它支持通过索引值去随机访问

Integer val = null;
int size = arrayList.size;
for(int i = 0;i<size;i++){
val = <Integer>arrayList.get(i)
}

3,第三种,常用for循环

Integer val = null;
for(Integer inter:arrayList){
	val = inter;
}

猜你喜欢

转载自blog.csdn.net/weixin_43352406/article/details/87971942
今日推荐