Java集合系列(2)--ArrayList
2017-02-13 15:30
309 查看
一、ArrayList的基本概述
ArrayList是一个数组队列,也就是动态数组,其容量能自动生长,它继承于AbstractList,实现了List, RandomAccess, Cloneable, java.io.Serializable这些接口。 实现了List接口,因此可以使用增加、删除修改、遍历等方法;实现了Serializable接口,因此它支持序列化,能够通过序列化传输;实现了RandomAccess接口,支持快速随机访问,实际上就是通过下标序号进行快速访问,实现了Cloneable接口,能被克隆,得到副本数据。 每个ArrayList实例都有一个容量,该容量是指用来存储列表元素的数组的大小。它总是至少等于列表的大小。随着向ArrayList中不断添加元素,其容量也自动增长。自动增长会带来数据向新数组的重新拷贝,因此,如果可预知数据量的多少,可在构造ArrayList时指定其容量。在添加大量元素前,应用程序也可以使用ensureCapacity操作来增加ArrayList实例的容量,这可以减少递增式再分配的数量。 ArrayList不是线程安全的,通常用在单线程环境下,在多线程环境下,可以考虑使用Collections.synchronizedList(List l)函数返回一个线程安全的ArrayList类,也可以使用concurrent并发包下的CopyOnWriteArrayList类,而且ArrayList中允许元素为null。 面试易考点:
关注点 | 结论 |
---|---|
集合底层实现的数据结构 | 动态数组 |
集合中元素是否允许为空 | 可以为空 |
是否允许数据重复 | 允许重复 |
是否有序 | 有序 |
是否线程安全 | 非线程安全(不是同步的) |
二、ArrayList的数据结构
(1)两个重要对象/** * 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;
ArrayList包含了两个重要的对象:elementData 和 size。
elementData 是”Object[]类型的数组”,它保存了添加到ArrayList中的元素。实际上,elementData是个动态数组,我们能通过构造函数 ArrayList(intinitialCapacity)来执行它的初始容量为initialCapacity;如果通过不含参数的构造函数ArrayList()来创建ArrayList,则elementData的容量默认是10。elementData数组的大小会根据ArrayList容量的增长而动态的增长,具体的增长方式,请参考源码分析中的ensureCapacity()函数。
size 则是动态数组的实际大小。
有个关键字需要解释:transient。
transient中文意思为短暂的吗,转瞬的。
Java的serializable提供了一种持久化对象实例的机制。当持久化对象时,可能有一个特殊的对象数据成员,我们不想用Serializable序列化机制来保存它。为了在一个特定对象的一个域上关闭Serializable,可以在这个域前加上关键字transient。
下面根据代码分析:
import java.io.Serializable; /** * Created by LKL on 2017/2/13. */ public class User implements Serializable { private String username; private transient String password; public User(String username, String password) { this.username = username; this.password = password; } public String toString() { return "username=" + username + ", password=" + password; } }
import java.io.*; /** * Created by LKL on 2017/2/13. */ public class TestTransient { public static void main(String[] args) { User user = new User("hust", "1234"); System.out.println(user); try { // 序列化,User对象中password被设置为transient的属性没有被序列化 ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream( "User.out")); out.writeObject(user); out.close(); } catch (Exception e) { e.printStackTrace(); } try { // 重新读取内容 ObjectInputStream in = new ObjectInputStream(new FileInputStream( "User.out")); User readUser = (User) in.readObject(); //读取后password的内容为null System.out.println(readUser.toString()); } catch (Exception e) { e.printStackTrace(); } } }
当在User的password属性上添加transient修饰,编译结果为:
username=hust, password=1234 username=hust, password=null
当在User的password属性上去掉transient修饰,编译结果为:
username=hust, password=1234 username=hust, password=1234
通过编译结果很容易得出,当添加了transient修饰后,读取password成员变量一次后,第二次再读取时,显然已经为空了,不再是持久化属性值,意为“短暂,暂时之意”;而没有了transient修饰,再次读取时,成员变量的值并没改变。即被标记为transient的属性在对象被序列化的时候不会被保存。
三、ArrayList的API
1>构造方法ArrayList提供了三种方式的构造器,可以构造一个默认初始容量为10的空列表、构造一个指定初始容量的空列表以及构造一个包含指定collection的元素的列表,这些元素按照该collection的迭代器返回它们的顺序排列的。
// ArrayList无参构造函数。默认容量是10。 public ArrayList() { this(10); } // ArrayList带容量大小的构造函数。 public ArrayList(int initialCapacity) { super(); if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); // 新建一个数组 this.elementData = new Object[initialCapacity]; } // 创建一个包含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); }
2>元素存储
ArrayList提供了set(int index, E element)、add(E e)、add(int index, E element)、addAll(Collection
// 用指定的元素替代此列表中指定位置上的元素,并返回以前位于该位置上的元素。 public E set(int index, E element) { RangeCheck(index); E oldValue = (E) elementData[index]; elementData[index] = element; return oldValue; } // 将指定的元素添加到此列表的==尾部==。 public boolean add(E e) { ensureCapacity(size + 1); elementData[size++] = e; return true; } // 将指定的元素插入此列表中的指定位置。 // 如果当前位置有元素,则向右移动当前位于该位置的元素以及所有后续元素(将其索引加1)。 public void add(int index, E element) { if (index > size || index < 0) throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size); // 如果数组长度不足,将进行扩容。 ensureCapacity(size+1); // Increments modCount!! // 将 elementData中从Index位置开始、长度为size-index的元素, // 拷贝到从下标为index+1位置开始的新的elementData数组中。 // 即将当前位于该位置的元素以及所有后续元素右移一个位置。 System.arraycopy(elementData, index, elementData, index + 1, size - index); elementData[index] = element; size++; } // 按照指定collection的迭代器所返回的元素顺序,将该collection中的所有元素添加到此列表的尾部。 public boolean addAll(Collection<? extends E> c) { Object[] a = c.toArray(); int numNew = a.length; ensureCapacity(size + numNew); // Increments modCount System.arraycopy(a, 0, elementData, size, numNew); size += numNew; return numNew != 0; } // 从指定的位置开始,将指定collection中的所有元素插入到此列表中。 public boolean addAll(int index, Collection<? extends E> c) { if (index > size || index < 0) throw new IndexOutOfBoundsException( "Index: " + index + ", Size: " + size); Object[] a = c.toArray(); int numNew = a.length; ensureCapacity(size + numNew); // Increments modCount int numMoved = size - index; if (numMoved > 0) System.arraycopy(elementData, index, elementData, index + numNew, numMoved); System.arraycopy(a, 0, elementData, index, numNew); size += numNew; return numNew != 0; }
常用的有add(E e),add(int index, E element)注意与Set集合中add方法的不同,Set集合中元素不重复,因此执行add方法时,只有元素不存在的情况下才会添加。
3>元素读取
// 返回此列表中指定位置上的元素。 public E get(int index) { RangeCheck(index); return (E) elementData[index]; }
4>截取子List
subList(int fromIndex, int toIndex)是根据索引fromIndex和toIndex来获取父List的一个视图,注意,这里并不是创建了一个新的List,而只是原来List的部分数据的一个视图,subList的任何操作都会影响到原来的父List。
public List<E> subList(int fromIndex, int toIndex) { subListRangeCheck(fromIndex, toIndex, size); return new SubList(this, 0, fromIndex, toIndex); } static void subListRangeCheck(int fromIndex, int toIndex, int size) { if (fromIndex < 0) throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); if (toIndex > size) throw new IndexOutOfBoundsException("toIndex = " + toIndex); if (fromIndex > toIndex) throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); }
SubList是一个ArrayList内部的private类,构造函数如下:
SubList(AbstractList<E> parent, int offset, int fromIndex, int toIndex) { this.parent = parent; this.parentOffset = fromIndex; this.offset = offset + fromIndex; this.size = toIndex - fromIndex; this.modCount = ArrayList.this.modCount; }
这个SubList的任何操作都是基于ArrayList这个类的elementData这个数组来实现的,所以只是父类的一个子视图。所以需要额外注意这一点。
5>元素删除
ArrayList提供了根据下标或者指定对象两种方式的删除功能。如下:
romove(int index):
// 移除此列表中指定位置上的元素。 public E remove(int index) { //检查index范围 RangeCheck(index); //修改modCount modCount++; E oldValue = (E) elementData[index]; //保留将要被移除的元素,将移除位置之后的元素向前挪动一个位置,将list末尾元素置空(null),返回被移除的元素。 int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // Let gc do its work return oldValue; }
remove(Object o)
// 移除此列表中首次出现的指定元素(如果存在)。这是应为ArrayList中允许存放重复的元素。 public boolean remove(Object o) { // 由于ArrayList中允许存放null,因此下面通过两种情况来分别处理。 if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { // 类似remove(int index),移除列表中指定位置上的元素。 fastRemove(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++; int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // Let gc do its work }
removeRange(int fromIndex,int toIndex)
protected void removeRange(int fromIndex, int toIndex) { modCount++; int numMoved = size - toIndex; System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved); // Let gc do its work int newSize = size - (toIndex-fromIndex); while (size != newSize) elementData[--size] = null; }
执行过程是将elementData从toIndex位置开始的元素向前移动到fromIndex,然后将toIndex位置之后的元素全部置空顺便修改size。
6>调整数组容量ensureCapacity:
从上面介绍的向ArrayList中存储元素的代码中,我们知道,每当向数组中添加元素时,都要去检查添加后元素的个数是否会超出当前数组的长度,如果超出,数组将会进行扩容,以满足添加数据的需求。数组扩容通过一个公开的方法ensureCapacity(int minCapacity)来实现。在实际添加大量元素前,我们也可以使用ensureCapacity来手动增加ArrayList实例的容量,以减少递增式再分配的数量。
public void ensureCapacity(int minCapacity) { modCount++; int oldCapacity = elementData.length; if (minCapacity > oldCapacity) { Object oldData[] = elementData; int newCapacity = (oldCapacity * 3)/2 + 1; //增加50%+1 if (newCapacity < minCapacity) newCapacity = minCapacity; // minCapacity is usually close to size, so this is a win: elementData = Arrays.copyOf(elementData, newCapacity); } }
从上述代码中可以看出,数组进行扩容时,会将老数组中的元素重新拷贝一份到新的数组中,每次数组容量的增长大约是其原容量的1.5倍。这种操作的代价是很高的,因此在实际使用时,我们应该尽量避免数组容量的扩张。当我们可预知要保存的元素的多少时,要在构造ArrayList实例时,就指定其容量,以避免数组扩容的发生。或者根据实际需求,通过调用ensureCapacity方法来手动增加ArrayList实例的容量。 注意点: Object oldData[] = elementData;//为什么要用到oldData[]
简单来看后面并没有用到关于oldData, 仔细分析哈,这就涉及到内存管理的类, 所以要了解内部的问题。 而且为什么这一句还在if的内部,这跟elementData = Arrays.copyOf(elementData, newCapacity); 这句是有关系的,下面这句Arrays.copyOf的实现时新创建了newCapacity大小的内存,然后把老的elementData放入。好像也没有用到oldData,有什么问题呢。问题就在于旧的内存的引用是elementData, elementData指向了新的内存块,如果有一个局部变量oldData变量引用旧的内存块的话,在copy的过程中就会比较安全,因为这样证明这块老的内存依然有引用,分配内存的时候就不会被侵占掉,然后copy完成后,这个局部变量的生命期也过去了,然后释放才是安全的。不然在copy的的时候,当新的内存或其他线程的分配内存侵占了这块老的内存,而copy还没有结束,这将是个严重的事情。
7)转换为静态数组toArray
ArrayList两个转为为静态数组的方法:
a、调用Arrays.copyOf将返回一个数组,数组内容是size个elementData的元素,即拷贝elementData从0至size-1位置的元素到新数组并返回。
public Object[] toArray() { return Arrays.copyOf(elementData, size); }
b、如果传入数组的长度小于size,返回一个新的数组,大小为size,类型与传入数组相同;所传入数组长度与size相等,则将elementData复制到传入数组中并返回传入的数组;若传入数组长度大于size,除了复制elementData外,还将把返回数组的第size个元素置为空。
public <T> T[] toArray(T[] a) { if (a.length < size) // Make a new array of a's runtime type, but my contents: return (T[]) Arrays.copyOf(elementData, size, a.getClass()); System.arraycopy(elementData, 0, a, 0, size); if (a.length > size) a[size] = null; return a; }
Fail-Fast机制:
ArrayList采用了快速失败的机制,通过记录modCount参数来实现。在面对并发的修改时,迭代器很快就会完全失败,而不是冒着在将来某个不确定时间发生任意不确定行为的风险。
补充:
一、ArrayList,优势在于随机访问元素,但是在List的中间插入和移除元素时较慢;LinkedList,通过代价较低的在List中间进行的插入和删除操作,提高了优化的顺序访问,而在随机访问方面相对比较慢。二、注意扩充容量的方法ensureCapacity。ArrayList在每次增加元素(可能是1个,也可能是一组)时,都要调用该方法来确保足够的容量。当容量不足以容纳当前的元素个数时,就设置新的容量为旧的容量的1.5倍加1,如果设置后的新容量还不够,则直接新容量设置为传入的参数(也就是所需的容量),而后用Arrays.copyof()方法将元素拷贝到新的数组。可以看出,当容量不够时,每次增加元素,都要将原来的元素拷贝到一个新的数组中,非常之耗时,也因此建议在事先能确定元素数量的情况下,才使用ArrayList,否则建议使用LinkedList。
文章只是作为自己的学习笔记,借鉴了网上的许多案例,如果觉得阔以的话,希望可以和大家多交流,相互学习,在此谢过…