概要
上一章,我们学习了Collection的架构。这一章开始,我们对Collection的具体实现类进行讲解;首先,讲解List,而List中ArrayList又最为常用。因此,本章我们讲解ArrayList。先对ArrayList有个整体认识,再学习它的源码,最后再通过例子来学习如何使用它。内容包括:
第1部分 ArrayList简介
第2部分 ArrayList数据结构
第3部分 ArrayList源码解析(基于JDK1.6.0_45)
第4部分 ArrayList遍历方式
第5部分 toArray()异常
第6部分 ArrayList示例
转载请注明出处:http://www.cnblogs.com/skywang12345/p/3308556.html
第1部分 ArrayList介绍
ArrayList简介
ArrayList 是一个数组队列,相当于 动态数组。与Java中的数组相比,它的容量能动态增长。它继承于AbstractList,实现了List, RandomAccess, Cloneable, java.io.Serializable这些接口。
ArrayList 继承了AbstractList,实现了List。它是一个数组队列,提供了相关的添加、删除、修改、遍历等功能。
ArrayList 实现了RandmoAccess接口,即提供了随机访问功能。RandmoAccess是java中用来被List实现,为List提供快速访问功能的。在ArrayList中,我们即可以通过元素的序号快速获取元素对象;这就是快速随机访问。稍后,我们会比较List的“快速随机访问”和“通过Iterator迭代器访问”的效率。
ArrayList 实现了Cloneable接口,即覆盖了函数clone(),能被克隆。
ArrayList 实现java.io.Serializable接口,这意味着ArrayList支持序列化,能通过序列化去传输。
和Vector不同,ArrayList中的操作不是线程安全的!所以,建议在单线程中才使用ArrayList,而在多线程中可以选择Vector或者CopyOnWriteArrayList。
ArrayList构造函数
// 默认构造函数 ArrayList() // capacity是ArrayList的默认容量大小。当由于增加数据导致容量不足时,容量会添加上一次容量大小的一半。 ArrayList(int capacity) // 创建一个包含collection的ArrayList ArrayList(Collection<? extends E> collection)
ArrayList的API
1 // Collection中定义的API 2 boolean add(E object) 3 boolean addAll(Collection<? extends E> collection) 4 void clear() 5 boolean contains(Object object) 6 boolean containsAll(Collection<?> collection) 7 boolean equals(Object object) 8 int hashCode() 9 boolean isEmpty() 10 Iterator<E> iterator() 11 boolean remove(Object object) 12 boolean removeAll(Collection<?> collection) 13 boolean retainAll(Collection<?> collection) 14 int size() 15 <T> T[] toArray(T[] array) 16 Object[] toArray() 17 // AbstractCollection中定义的API 18 void add(int location, E object) 19 boolean addAll(int location, Collection<? extends E> collection) 20 E get(int location) 21 int indexOf(Object object) 22 int lastIndexOf(Object object) 23 ListIterator<E> listIterator(int location) 24 ListIterator<E> listIterator() 25 E remove(int location) 26 E set(int location, E object) 27 List<E> subList(int start, int end) 28 // ArrayList新增的API 29 Object clone() 30 void ensureCapacity(int minimumCapacity) 31 void trimToSize() 32 void removeRange(int fromIndex, int toIndex)