加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

ArrayList 简单介绍

发布时间:2020-12-14 06:36:21 所属栏目:Java 来源:网络整理
导读:这里是修真院后端小课堂,每篇分享文从 【背景介绍】【知识剖析】【常见问题】【解决方案】【编码实战】【扩展思考】【更多讨论】【参考文献】 八个方面深度解析后端知识/技能,本篇分享的是: 【ArrayList 简单介绍 】 大家好,我是IT修真院北京分院第27期

这里是修真院后端小课堂,每篇分享文从

【背景介绍】【知识剖析】【常见问题】【解决方案】【编码实战】【扩展思考】【更多讨论】【参考文献】

八个方面深度解析后端知识/技能,本篇分享的是:

【ArrayList 简单介绍 】

大家好,我是IT修真院北京分院第27期的JAVA学员,一枚正直纯洁善良的java程序员。

今天给大家分享一下,修真院官网Java任务10,深度思考中的知识点———ArrayList 简单介绍

1.背景介绍

概括的说,ArrayList 是一个动态数组,它是线程不安全的,允许元素为null。? 其底层数据结构依然是数组,它实现了List,RandomAccess,Cloneable,java.io.Serializable接口,其中RandomAccess代表了其拥有随机快速访问的能力,ArrayList可以以O(1)的时间复杂度去根据下标访问元素。

因其底层数据结构是数组,所以可想而知,它是占据一块连续的内存空间(容量就是数组的length),所以它也有数组的缺点,空间效率不高。

由于数组的内存连续,可以根据下标以O1的时间读写(改查)元素,因此时间效率很高。

当集合中的元素超出这个容量,便会进行扩容操作。扩容操作也是ArrayList 的一个性能消耗比较大的地方,所以若我们可以提前预知数据的规模,应该通过public ArrayList(int initialCapacity) {}构造方法,指定集合的大小,去构建ArrayList实例,以减少扩容次数,提高效率。

或者在需要扩容的时候,手动调用public void ensureCapacity(int minCapacity) {}方法扩容。? 不过该方法是ArrayList的API,不是List接口里的,所以使用时需要强转:? ((ArrayList)list).ensureCapacity(30);

当每次修改结构时,增加导致扩容,或者删,都会修改modCount。

2.知识剖析

构造方法 ? ? //默认构造函数里的空数组 ? ? private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

? ? //存储集合元素的底层实现:真正存放元素的数组 ? ? transient Object[] elementData; // non-private to simplify nested class access ? ? //当前元素数量 ? ? private int size;

? ? //默认构造方法 ? ? public ArrayList() { ? ? ? ? //默认构造方法只是简单的将 空数组赋值给了elementData ? ? ? ? this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; ? ? }

? ? //空数组 ? ? private static final Object[] EMPTY_ELEMENTDATA = {}; ? ? //带初始容量的构造方法 ? ? public ArrayList(int initialCapacity) { ? ? ? ? //如果初始容量大于0,则新建一个长度为initialCapacity的Object数组. ? ? ? ? //注意这里并没有修改size(对比第三个构造函数) ? ? ? ? if (initialCapacity > 0) { ? ? ? ? ? ? this.elementData = new Object[initialCapacity]; ? ? ? ? } else if (initialCapacity == 0) {//如果容量为0,直接将EMPTY_ELEMENTDATA赋值给elementData ? ? ? ? ? ? this.elementData = EMPTY_ELEMENTDATA; ? ? ? ? } else {//容量小于0,直接抛出异常 ? ? ? ? ? ? throw new IllegalArgumentException("Illegal Capacity: "+ ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?initialCapacity); ? ? ? ? } ? ? }

? ? //利用别的集合类来构建ArrayList的构造函数 ? ? public ArrayList(Collection c) { ? ? ? ? //直接利用Collection.toArray()方法得到一个对象数组,并赋值给elementData? ? ? ? ? elementData = c.toArray(); ? ? ? ? //因为size代表的是集合元素数量,所以通过别的集合来构造ArrayList时,要给size赋值 ? ? ? ? if ((size = elementData.length) != 0) { ? ? ? ? ? ? // c.toArray might (incorrectly) not return Object[] (see 6260652) ? ? ? ? ? ? if (elementData.getClass() != Object[].class)//这里是当c.toArray出错,没有返回Object[]时,利用Arrays.copyOf 来复制集合c中的元素到elementData数组中 ? ? ? ? ? ? ? ? elementData = Arrays.copyOf(elementData,size,Object[].class); ? ? ? ? } else { ? ? ? ? ? ? //如果集合c元素数量为0,则将空数组EMPTY_ELEMENTDATA赋值给elementData? ? ? ? ? ? ? // replace with empty array. ? ? ? ? ? ? this.elementData = EMPTY_ELEMENTDATA; ? ? ? ? } ? ? } 小结一下,构造函数走完之后,会构建出数组elementData和数量size。

这里大家要注意一下Collection.toArray()这个方法,在Collection子类各大集合的源码中,高频使用了这个方法去获得某Collection的所有元素。

关于方法:Arrays.copyOf(elementData,Object[].class),就是根据class的类型来决定是new 还是反射去构造一个泛型数组,同时利用native函数,批量赋值元素至新数组中。? 如下:

? ? public static T[] copyOf(U[] original,int newLength,Class newType) { ? ? ? ? @SuppressWarnings("unchecked") ? ? ? ? //根据class的类型来决定是new 还是反射去构造一个泛型数组 ? ? ? ? T[] copy = ((Object)newType == (Object)Object[].class) ? ? ? ? ? ? ? (T[]) new Object[newLength] ? ? ? ? ? ? : (T[]) Array.newInstance(newType.getComponentType(),newLength); ? ? ? ? //利用native函数,批量赋值元素至新数组中。 ? ? ? ? System.arraycopy(original,copy, ? ? ? ? ? ? ? ? ? ? ? ? ?Math.min(original.length,newLength)); ? ? ? ? return copy; ? ? } 值得注意的是,System.arraycopy也是一个很高频的函数,大家要留意一下。

? ? public static native void arraycopy(Object src,?int ?srcPos, ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Object dest,int destPos, ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? int length);

常用API 1 增 每次 add之前,都会判断add后的容量,是否需要扩容。

public boolean add(E e) { ? ? ensureCapacityInternal(size + 1); ?// Increments modCount!! ? ? elementData[size++] = e;//在数组末尾追加一个元素,并修改size ? ? return true; } ? ? private static final int DEFAULT_CAPACITY = 10;//默认扩容容量 10 ? ? private void ensureCapacityInternal(int minCapacity) { ? ? ? ? //利用 == 可以判断数组是否是用默认构造函数初始化的 ? ? ? ? if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { ? ? ? ? ? ? minCapacity = Math.max(DEFAULT_CAPACITY,minCapacity); ? ? ? ? }

? ? ? ? ensureExplicitCapacity(minCapacity); ? ? }

private void ensureExplicitCapacity(int minCapacity) { ? ? modCount++;//如果确定要扩容,会修改modCount?

? ? // overflow-conscious code ? ? if (minCapacity - elementData.length > 0) ? ? ? ? grow(minCapacity); }

//需要扩容的话,默认扩容一半 private void grow(int minCapacity) { ? ? // overflow-conscious code ? ? int oldCapacity = elementData.length; ? ? int newCapacity = oldCapacity + (oldCapacity >> 1);//默认扩容一半 ? ? if (newCapacity - minCapacity < 0)//如果还不够 ,那么就用 能容纳的最小的数量。(add后的容量) ? ? ? ? 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);//拷贝,扩容,构建一个新数组, } ?

public void add(int index,E element) { ? ? rangeCheckForAdd(index);//越界判断 如果越界抛异常

? ? ensureCapacityInternal(size + 1); ?// Increments modCount!! ? ? System.arraycopy(elementData,index,elementData,index + 1, ? ? ? ? ? ? ? ? ? ? ?size - index); //将index开始的数据 向后移动一位 ? ? elementData[index] = element; ? ? size++; } public boolean addAll(Collection c) { ? ? Object[] a = c.toArray(); ? ? int numNew = a.length; ? ? ensureCapacityInternal(size + numNew); ?// Increments modCount //确认是否需要扩容 ? ? System.arraycopy(a,numNew);// 复制数组完成复制 ? ? size += numNew; ? ? return numNew != 0; } public boolean addAll(int index,Collection c) { ? ? rangeCheckForAdd(index);//越界判断

? ? Object[] a = c.toArray(); ? ? int numNew = a.length; ? ? ensureCapacityInternal(size + numNew); ?// Increments modCount //确认是否需要扩容

? ? int numMoved = size - index; ? ? if (numMoved > 0) ? ? ? ? System.arraycopy(elementData,index + numNew, ? ? ? ? ? ? ? ? ? ? ? ? ?numMoved);//移动(复制)数组

? ? System.arraycopy(a,numNew);//复制数组完成批量赋值 ? ? size += numNew; ? ? return numNew != 0; } 总结:? add、addAll。? 先判断是否越界,是否需要扩容。? 如果扩容, 就复制数组。? 然后设置对应下标元素值。

值得注意的是:? 1 如果需要扩容的话,默认扩容一半。如果扩容一半不够,就用目标的size作为扩容后的容量。? 2 在扩容成功后,会修改modCount

2 删 public E remove(int index) { ? ? rangeCheck(index);//判断是否越界 ? ? modCount++;//修改modeCount 因为结构改变了 ? ? E oldValue = elementData(index);//读出要删除的值 ? ? int numMoved = size - index - 1; ? ? if (numMoved > 0) ? ? ? ? System.arraycopy(elementData,index+1, ? ? ? ? ? ? ? ? ? ? ? ? ?numMoved);//用复制 覆盖数组数据 ? ? elementData[--size] = null; // clear to let GC do its work ?//置空原尾部数据 不再强引用, 可以GC掉 ? ? return oldValue; } ? ? //根据下标从数组取值 并强转 ? ? E elementData(int index) { ? ? ? ? return (E) elementData[index]; ? ? }

//删除该元素在数组中第一次出现的位置上的数据。 如果有该元素返回true,如果false。 public boolean remove(Object o) { ? ? if (o == null) { ? ? ? ? for (int index = 0; index < size; index++) ? ? ? ? ? ? if (elementData[index] == null) { ? ? ? ? ? ? ? ? fastRemove(index);//根据index删除元素 ? ? ? ? ? ? ? ? return true; ? ? ? ? ? ? } ? ? } else { ? ? ? ? for (int index = 0; index < size; index++) ? ? ? ? ? ? if (o.equals(elementData[index])) { ? ? ? ? ? ? ? ? fastRemove(index); ? ? ? ? ? ? ? ? return true; ? ? ? ? ? ? } ? ? } ? ? return false; } //不会越界 不用判断 ,也不需要取出该元素。 private void fastRemove(int index) { ? ? modCount++;//修改modCount ? ? int numMoved = size - index - 1;//计算要移动的元素数量 ? ? if (numMoved > 0) ? ? ? ? System.arraycopy(elementData, ? ? ? ? ? ? ? ? ? ? ? ? ?numMoved);//以复制覆盖元素 完成删除 ? ? elementData[--size] = null; // clear to let GC do its work ?//置空 不再强引用 }

//批量删除 public boolean removeAll(Collection c) { ? ? Objects.requireNonNull(c);//判空 ? ? return batchRemove(c,false); } //批量移动 private boolean batchRemove(Collection c,boolean complement) { ? ? final Object[] elementData = this.elementData; ? ? int r = 0,w = 0;//w 代表批量删除后 数组还剩多少元素 ? ? boolean modified = false; ? ? try { ? ? ? ? //高效的保存两个集合公有元素的算法 ? ? ? ? for (; r < size; r++) ? ? ? ? ? ? if (c.contains(elementData[r]) == complement) // 如果 c里不包含当前下标元素,? ? ? ? ? ? ? ? ? elementData[w++] = elementData[r];//则保留 ? ? } finally { ? ? ? ? // Preserve behavioral compatibility with AbstractCollection, ? ? ? ? // even if c.contains() throws. ? ? ? ? if (r != size) { //出现异常会导致 r !=size,则将出现异常处后面的数据全部复制覆盖到数组里。 ? ? ? ? ? ? System.arraycopy(elementData,r, ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?elementData,w, ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?size - r); ? ? ? ? ? ? w += size - r;//修改 w数量 ? ? ? ? } ? ? ? ? if (w != size) {//置空数组后面的元素 ? ? ? ? ? ? // clear to let GC do its work ? ? ? ? ? ? for (int i = w; i < size; i++) ? ? ? ? ? ? ? ? elementData[i] = null; ? ? ? ? ? ? modCount += size - w;//修改modCount ? ? ? ? ? ? size = w;// 修改size ? ? ? ? ? ? modified = true; ? ? ? ? } ? ? } ? ? return modified; } 从这里我们也可以看出,当用来作为删除元素的集合里的元素多余被删除集合时,也没事,只会删除它们共同拥有的元素。

小结:? 1 删除操作一定会修改modCount,且可能涉及到数组的复制,相对低效。? 2 批量删除中,涉及高效的保存两个集合公有元素的算法,可以留意一下。

3 改 不会修改modCount,相对增删是高效的操作。

public E set(int index,E element) { ? ? rangeCheck(index);//越界检查 ? ? E oldValue = elementData(index); //取出元素? ? ? elementData[index] = element;//覆盖元素 ? ? return oldValue;//返回元素 } 4 查 不会修改modCount,相对增删是高效的操作。

public E get(int index) { ? ? rangeCheck(index);//越界检查 ? ? return elementData(index); //下标取数据 } E elementData(int index) { ? ? return (E) elementData[index]; } 5 清空,clear 会修改modCount。

public void clear() { ? ? modCount++;//修改modCount ? ? // clear to let GC do its work ? ? for (int i = 0; i < size; i++) ?//将所有元素置null ? ? ? ? elementData[i] = null;

? ? size = 0; //修改size? } 6 包含 contain //普通的for循环寻找值,只不过会根据目标对象是否为null分别循环查找。 public boolean contains(Object o) { ? ? return indexOf(o) >= 0; } //普通的for循环寻找值,只不过会根据目标对象是否为null分别循环查找。 public int indexOf(Object o) { ? ? if (o == null) { ? ? ? ? for (int i = 0; i < size; i++) ? ? ? ? ? ? if (elementData[i]==null) ? ? ? ? ? ? ? ? return i; ? ? } else { ? ? ? ? for (int i = 0; i < size; i++) ? ? ? ? ? ? if (o.equals(elementData[i])) ? ? ? ? ? ? ? ? return i; ? ? } ? ? return -1; } 7 判空 isEmpty() public boolean isEmpty() { ? ? return size == 0; } 8 迭代器 Iterator. public Iterator iterator() { ? ? return new Itr(); } /** ?* An optimized version of AbstractList.Itr ?*/ private class Itr implements Iterator { ? ? int cursor; ? ? ? // index of next element to return //默认是0 ? ? int lastRet = -1; // index of last element returned; -1 if no such ?//上一次返回的元素 (删除的标志位) ? ? int expectedModCount = modCount; //用于判断集合是否修改过结构的 标志

? ? public boolean hasNext() { ? ? ? ? return cursor != size;//游标是否移动至尾部 ? ? }

? ? @SuppressWarnings("unchecked") ? ? public E next() { ? ? ? ? checkForComodification(); ? ? ? ? int i = cursor; ? ? ? ? if (i >= size)//判断是否越界 ? ? ? ? ? ? throw new NoSuchElementException(); ? ? ? ? Object[] elementData = ArrayList.this.elementData; ? ? ? ? if (i >= elementData.length)//再次判断是否越界,在 我们这里的操作时,有异步线程修改了List ? ? ? ? ? ? throw new ConcurrentModificationException(); ? ? ? ? cursor = i + 1;//游标+1 ? ? ? ? return (E) elementData[lastRet = i];//返回元素 ,并设置上一次返回的元素的下标 ? ? }

? ? public void remove() {//remove 掉 上一次next的元素 ? ? ? ? if (lastRet < 0)//先判断是否next过 ? ? ? ? ? ? throw new IllegalStateException(); ? ? ? ? checkForComodification();//判断是否修改过

? ? ? ? try { ? ? ? ? ? ? ArrayList.this.remove(lastRet);//删除元素 remove方法内会修改 modCount 所以后面要更新Iterator里的这个标志值 ? ? ? ? ? ? cursor = lastRet; //要删除的游标 ? ? ? ? ? ? lastRet = -1; //不能重复删除 所以修改删除的标志位 ? ? ? ? ? ? expectedModCount = modCount;//更新 判断集合是否修改的标志, ? ? ? ? } catch (IndexOutOfBoundsException ex) { ? ? ? ? ? ? throw new ConcurrentModificationException(); ? ? ? ? } ? ? } //判断是否修改过了List的结构,如果有修改,抛出异常 ? ? final void checkForComodification() { ? ? ? ? if (modCount != expectedModCount) ? ? ? ? ? ? throw new ConcurrentModificationException(); ? ? } } ?

3.常见问题

Vector底层也是数组,与ArrayList最大的区别就是:同步(线程安全) Vector是同步的,我们可以从方法上就可以看得出来

如果非要实现同步呢?

4.解决方案

在要求非同步的情况下,我们一般都是使用ArrayList来替代Vector的了~ 如果想要ArrayList实现同步,可以使用Collections的方法:List list = Collections.synchronizedList(new ArrayList(...));,就可以实现同步了~ ArrayList在底层数组不够用时在原来的基础上扩展0.5倍,Vector是扩展1倍

5.编码实战

详见视频

6.扩展思考

ARRAYLIST集合加入1万条数据,应该怎么提高效率

ArrayList的默认初始容量为10,要插入大量数据的时候需要不断扩容,而扩容是非常影响性能的。 因此,现在明确了10万条数据了,我们可以直接在初始化的时候就设置ArrayList的容量! 这样就可以提高效率

7.????参考文献

List集合就这么简单【源码剖析】:

https://segmentfault.com/a/1190000014240704

8.????更多讨论

Q1:说出ArrayList,LinkedList的存储性能和特性 A1:ArrayList的底层是数组,LinkedList的底层是双向链表。 ArrayList它支持以角标位置进行索引出对应的元素(随机访问),而LinkedList则需要遍历整个链表来获取对应的元素。 因此一般来说ArrayList的访问速度是要比LinkedList要快的 ArrayList由于是数组,对于删除和修改而言消耗是比较大(复制和移动数组实现),LinkedList是双向链表删除和修改只需要修改对应的指针即可,消耗是很小的。 因此一般来说LinkedList的增删速度是要比ArrayList要快

Q2:什么情况下你会使用ArrayList?什么时候你会选择LinkedList? A2:多数情况下,当你遇到访问元素比插入或者是删除元素更加频繁的时候,你应该使用ArrayList。另外一方面,当你在某个特别的索引中,插入或者是删除元素更加频繁,或者你压根就不需要访问元素的时候,你会选择LinkedList。这里的主要原因是,在ArrayList中访问元素的最糟糕的时间复杂度是”1″,而在LinkedList中可能就是”n”了。在ArrayList中增加或者删除某个元素,通常会调用System.arraycopy方法,这是一种极为消耗资源的操作,因此,在频繁的插入或者是删除元素的情况下,LinkedList的性能会更加好一点。

Q3:如何复制某个ArrayList到另一个ArrayList中去?写出你的代码? A3:

下面就是把某个ArrayList复制到另一个ArrayList中去的几种技术:

  1. 使用clone()方法,比如ArrayList newArray = oldArray.clone();

  2. 使用ArrayList构造方法,比如:ArrayList myObject = new ArrayList(myTempObject);

  3. 使用Collection的copy方法。

?注意1和2是浅拷贝(shallow copy)。

今天的分享就到这里啦,欢迎大家点赞、转发、留言、拍砖~

PPT链接?视频链接

更多内容,可以加入IT交流群565734203与大家一起讨论交流

这里是技能树·IT修真院:,初学者转行到互联网的聚集地

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读