ArrayList
基于 JDK 1.8。
ArrayList 类的继承关系:
实现的接口
Collection
Collection 接口表示一个数据集合,数据间没有位置或顺序的概念,接口定义为:
public interface Collection<E> extends Iterable<E> {
int size();
boolean isEmpty();
boolean contains(Object o);
Iterator<E> iterator();
Object[] toArray();
<T> T[] toArray(T[] a);
boolean add(E e);
boolean remove(Object o);
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c);
boolean removeAll(Collection<?> c);
boolean retainAll(Collection<?> c);
void clear();
boolean equals(Object o);
int hashCode();
}
这几个xxxAll()方法的含义基本也是可以顾名思义的,addAll添加,removeAll删除,containsAll检查是否包含了参数容器中的所有元素,只有全包含才返回true,retainAll**只保留参数容器中的元素**,其他元素会进行删除。
有一个抽象类AbstractCollection对这几个方法都提供了默认实现,实现的方式就是利用迭代器方法逐个操作,比如说,我们看removeAll方法,代码为:
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
boolean modified = false;
Iterator<?> it = iterator();
while (it.hasNext()) {
if (c.contains(it.next())) {
it.remove();
modified = true;
}
}
return modified;
}
ArrayList继承了AbstractList,而AbstractList又继承了AbstractCollection,ArrayList对其中一些方法进行了重写,以提供更为高效的实现。
List
List表示有顺序或位置的数据集合,它扩展了Collection 接口,增加的主要方法有:
boolean addAll(int index, Collection<? extends E> c);
E get(int index);
E set(int index, E element);
void add(int index, E element);
E remove(int index);
int indexOf(Object o);
int lastIndexOf(Object o);
ListIterator<E> listIterator();
ListIterator<E> listIterator(int index);
List<E> subList(int fromIndex, int toIndex);
RandomAccess
RandomAccess的定义为:
public interface RandomAccess {
}
没有定义任何代码。这种没有任何代码的接口被称之为标记接口,用于声明类的一种属性。
该接口部分 javadoc:The primary purpose of this interface is to allow generic algorithms to alter their behavior to provide good performance when applied to either random or sequential access lists.
即实现了RandomAccess接口的类表示可以随机访问,可随机访问就是可以根据索引值就可以直接定位到具体的元素。并且一些通用的算法代码中,它可以根据这个声明而选择效率更高的实现。例如,Collections类中有一个方法binarySearch,在List中进行二分查找,它的实现代码就根据list是否实现了RandomAccess而采用不同的实现机制:
public static <T>
int binarySearch(List<? extends Comparable<? super T>> list, T key) {
if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)
return Collections.indexedBinarySearch(list, key);
else
return Collections.iteratorBinarySearch(list, key);
}
Serializable
它也是一个标记接口。实现该接口的类是可序列化的。没有实现此接口的类将不能使它们的任意状态被序列化或逆序列化。
构造函数
ArrayList是一个泛型容器,新建ArrayList需要实例化泛型参数:
ArrayList<Integer> intList = new ArrayList<>(10);
ArrayList<Double> doubleList = new ArrayList<>();
ArrayList<String> strList = new ArrayList<>(