ArrayList
上一篇主要是对Collection的部分源码进行了学习,这一章学习一下ArrayList。ArrayList是List中最常用的部分。首先,先看一下ArrayList的设计结构图,如图:
通过结构图可以看出ArrayList与Collection之间的关系。先来看一下源码中对ArrayList类的定义
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{}
从类的定义和图中的关系,可以看出ArrayList继承了AbstractList并实现了List。它是一个用数组封装好的类,是一个动态的数组,可以自由的扩容。Api中提供了相关的添加,删除,遍历,修改等功能。
ArrayList实现了RandomAccess接口,即提供了随机访问功能。RandomAccess是java中用来被List实现,为List提供快速访问功能的。在ArrayList中,我们即可以通过元素的序号来快速获取元素对象,这就是快速随机访问。下文会比较List的“快速随机访问”和使用“Iterator迭代器访问”的效率。
ArrayList实现了Cloneable接口,即覆盖了函数clone(),能被克隆。
ArrayList实现了java.io.Serializable接口,这意味着ArrayList支持序列化,能通过序列化去传输。
通过类中定义的方法,看一下里面的Api
//有参构造方法,设置list的容量
public ArrayList(int initialCapacity)
//无惨构造方法
public ArrayList()
//创建一个Collection类型的ArrayList
public ArrayList(Collection<? extends E> c)
// Collection中定义的API
boolean add(E object)
boolean addAll(Collection<? extends E> collection)
void clear()
boolean contains(Object object)
boolean containsAll(Collection<?> collection)
boolean equals(Object object)
int hashCode()
boolean isEmpty()
Iterator<E> iterator()
boolean remove(Object object)
boolean removeAll(Collection<?> collection)
boolean retainAll(Collection<?> collection)
int size()
<T> T[] toArray(T[] array)
Object[] toArray()
// AbstractCollection中定义的API
void add(int location, E object)
boolean addAll(int location, Collection<? extends E> collection)
E get(int location)
int indexOf(Object object)
int lastIndexOf(Object object)
ListIterator<E> listIterator(int location)
ListIterator<E> listIterator()
E remove(int location)
E set(int location, E object)
List<E> subList(int start, int end)
// ArrayList新增的API
Object clone()
void ensureCapacity(int minimumCapacity)
void trimToSize()
void removeRange(int fromIndex, int toIndex)
从源码中的Api中可以看出,里面的有其父类的api,也有自己新增的api。供集合list使用。源码中是实现方法,自己学习了一下,在这里就不在贴出来了。有兴趣的可以下载java源码看一下。以后有时间自己在认真的学习学习。
对ArrayList源码源码的学习总结,
1.ArrayList源码实现是一个数组,ArrayList初始化的容量是10。当ArrayList的容量不能满足需求的时候,ArrayList会自动的扩容。新的容量 = 原始容量 + 原始容量 / 2。
2.ArrayList实现了Cloneable(克隆),将所有的元素克隆岛数组中去。
3.ArrayList实现了RandomAccess,可以随机的访问。
4.ArrayList实现java.io.Serializable的方式。当写入到输出流时,先写入“容量”,再依次写出“每一个元素”;当读出输入流时,先读取“容量”,再依次读取“每一个元素”。
ArrayList的遍历
1). 通过迭代器遍历。即Iterator迭代器。
Integer value = null;
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
value = (Integer)iterator.next();
System.our.println(value)
}
2). 随机访问,通过索引值去遍历。由于ArrayList实现了RandomAccess接口,所以它支持通过索引值去随机访问元素。
Integer value = null;
int size = list.size();
for (int i = 0; i < size; i++) {
value = (Integer)list.get(i);
System.our.println(value)
}
3). 通过for循环遍历。
Integer value = null;
for (Integer integer : list) {
value = integer;
System.our.println(value)
}
以上是对ArrayList的简单学习,以后有时间在深入的学习。