Collection是一个接口,它是一个高度抽象出来的接口,定义了集合的基本操作: 添加、删除、清空、遍历、是否为空、获取大小等方法。我们来看看Collection接口的类图:

从图中我们可以看出,Collection接口主要有 2 个子分支: List和 Set,并且定义了 AbstractCollection抽象类让其他类继承,AbstractCollection实现了 Collection中的绝大部分方法;我们可以看出 AbstractList和 AbstractSet都继承于 AbstractCollection。
其次,我们看到 Collection接口依赖于 Iterator接口,(依赖关系:依赖就是一个类 A 使用到了另一个类 B,因此类 B 的变化会影响到类 A。比如某人要过河,需要借用一条船,此时人与船之间的关系就是依赖。表现在代码层面,为类 B 作为参数被类 A 在某个method方法中使用。)
Collection依赖于 Iterator,展现在源码中是 Collection接口定义了方法 Iterator<E> iterator(),用以返回集合的迭代器来遍历集合。在 List接口中,通过 listIterator()方法返回一个 ListIterator对象;ListIterator接口是 List特有的。
Collection接口的所有子类(直接子类和间接子类)都必须实现 2 种构造函数:无参构造函数 和 参数为 Collection的构造函数。带参数的构造函数可以用来转换 Collection的类型。下面是 Collection接口中定义的API(JDK1.8):
public interface Collection<E> extends Iterable<E> {
Iterator<E> iterator();
boolean add(E e);
boolean addAll(Collection<? extends E> c);
boolean remove(Object o);
boolean removeAll(Collection<?> c);
boolean contains(Object o);
boolean containsAll(Collection<?> c);
boolean retainAll(Collection<?> c);
int size();
boolean isEmpty();
<T> T[] toArray(T[] a);
void clear();
boolean equals(Object o);
int hashCode();
default <T> T[] toArray(IntFunction<T[]> generator) {
return toArray(generator.apply(0));
}
default boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
boolean removed = false;
final Iterator<E> each = iterator();
while (each.hasNext()) {
if (filter.test(each.next())) {
each.remove();
removed = true;
}
}
return removed;
}
@Override
default Spliterator<E> spliterator() {
return Spliterators.spliterator(this, 0);
}
default Stream<E> stream() {
return StreamSupport.stream(spliterator(), false);
}
default Stream<E> parallelStream() {
return StreamSupport.stream(spliterator(), true);
}
}
List接口的定义如下:
public interface List<E> extends Collection<E> {
}
从 List定义中可以看出,它继承于 Collection接口,即 List是集合的一种。List是有序的队列,可以存储重复元素,List中的每一个元素都有一个索引,第一个元素的索引值为0,往后的元素的索引值依次 + 1,List中允许有重复的元素。
让我们来看看 List集合相关的类图:

从类图中我们看到,List接口继承于 Collection接口,并且于下有一个抽象类 AbstractList以及后续的具体子类: ArrayList、LinkedList等。单纯从这一条链路 List ----> AbstractList ----> ArrayList/LinkedList来看,有一股 模板方法模式 的味道,顶层接口定义好了具体行为,抽象类提供了可复用的 算法骨架,然后具体子类根据自己的特点自定义实现相关功能。
回到 List上来,由于继承了 Collection接口,自然包含了其所有的API,但由于 List是有序集合,所以它也有自己额外的API:

从图中我们可以看出,List接口新增的API主要有:获取元素的get()、设置元素的 set()、以及符合自身有序集合的指定索引index的添加元素方法 add(int, E)、还有获取元素索引值的 indexOf相关方法等……
具体源码如下:
public interface List<E> extends Collection<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 addAll(int index, Collection<? extends E> c);
boolean removeAll(Collection<?> c);
boolean retainAll(Collection<?> c);
default void replaceAll(UnaryOperator<E> operator) {
Objects.requireNonNull(operator);
final ListIterator<E> li = this.listIterator();
while (li.hasNext()) {
li.set(operator.apply(li.next()));
}
}
@SuppressWarnings({"unchecked", "rawtypes"})
default void sort(Comparator<? super E> c) {
Object[] a = this.toArray();
Arrays.sort(a, (Comparator) c);
ListIterator<E> i = this.listIterator();
for (Object e : a) {
i.next();
i.set((E) e);
}
}
void clear();
boolean equals(Object o);
int hashCode();
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);
@Override
default Spliterator<E> spliterator() {
return Spliterators.spliterator(this, Spliterator.ORDERED);
}
}
AbstractSequentialList抽象类的定义如下:
public abstract class AbstractSequentialList<E> extends AbstractList<E> {
}
从其定义我们看看到它继承于 AbstractList抽象类,那它到底是做有什么实际上的用途呢?我们来看看它的API:

我们可以看到,它所重写的 API中大部分都含有参数:索引index。
AbstractSequentialList实现了本来只能 顺序访问/操作 的数据存储结构(例如:链表)的 get(int index)、 add(int index, E element)等 随机访问/操作 的方法。这句话可能有点绕,稍加解释一番:链表是一种只能顺序访问的数据存储结构,而 AbstractSequentialList抽象类对这类只能 顺序访问/操作 的数据存储结构,也提供了类数组般的随机访问/操作 的能力。其底层是基于迭代器顺序遍历(说到底还是需要遍历,只不过是它帮我们做了这一步~)来实现的。
一般情况下,对于支持随机访问的数据结构 (例如:ArrayList) 会继承 AbstractList抽象类,不支持随机访问的数据结构(例如: LinkedList)则会继承 AbstactSequentialList抽象类。但是需要注意的是: ArrayList和 LinkedList都大量重写了 AbstractList和 AbstactSequentialList的相关实现,可真是任性的小朋友呀。
Map的定义如下:
public interface Map<K,V> {
}
我们可以看到,Map接口并没有继承于 Collection;Map是一种把键对象(key)和 值对象(value)进行关联的容器。对于键对象(key)来说,像 Set一样,一个Map容器中的键对象不允许重复,也即键对象key是唯一的,同时一个 键对象key只能映射一个 值对象value。对于 值对象value并没有唯一性要求,理论上可以将多个 key都映射到同一个 value之上;虽然程序不会报错,但是可能会对使用者造成困扰(到底是哪个key映射过来的呢?)
注意:由于 Map中作为 key的对象将通过计算其散列函数来确定与之对应的存放 value的位置,因此任何作为 key的对象都必须实现hashCode和 equals方法。
我们来看看 Map集合的家庭成员有哪些:

从类图中我们可以看出,Map系列集合提供的可供使用的子类有 6 个,分别为: HashMap、LinkedHashMap、 WeakHashMap、HashTable(前朝遗孤)、IdentityHashMap以及 TreeMap;而实际的开发中,使用最为频繁的为: HashMap、LinkedHashMap以及 TreeMap。
后续的文章也会针对这 3 个 Map进行源码分析。
Map作为一个集合,所提供的功能始终跳不出这几种:新增、删除、查找等……我们来瞅瞅JDK设计者为其设计了哪些具体的API吧!

public interface Map<K,V> {
int size();
boolean isEmpty();
boolean containsKey(Object key);
boolean containsValue(Object value);
V get(Object key);
V put(K key, V value);
V remove(Object key);
void putAll(Map<? extends K, ? extends V> m);
void clear();
Set<K> keySet();
Collection<V> values();
Set<Map.Entry<K, V>> entrySet();
interface Entry<K,V> {
K getKey();
V getValue();
V setValue(V value);
boolean equals(Object o);
int hashCode();
public static <K extends Comparable<? super K>, V> Comparator<Map.Entry<K,V>> comparingByKey() {
return (Comparator<Map.Entry<K, V>> & Serializable)
(c1, c2) -> c1.getKey().compareTo(c2.getKey());
}
public static <K, V extends Comparable<? super V>> Comparator<Map.Entry<K,V>> comparingByValue() {
return (Comparator<Map.Entry<K, V>> & Serializable)
(c1, c2) -> c1.getValue().compareTo(c2.getValue());
}
public static <K, V> Comparator<Map.Entry<K, V>> comparingByKey(Comparator<? super K> cmp) {
Objects.requireNonNull(cmp);
return (Comparator<Map.Entry<K, V>> & Serializable)
(c1, c2) -> cmp.compare(c1.getKey(), c2.getKey());
}
public static <K, V> Comparator<Map.Entry<K, V>> comparingByValue(Comparator<? super V> cmp) {
Objects.requireNonNull(cmp);
return (Comparator<Map.Entry<K, V>> & Serializable)
(c1, c2) -> cmp.compare(c1.getValue(), c2.getValue());
}
}
boolean equals(Object o);
int hashCode();
default V getOrDefault(Object key, V defaultValue) {
V v;
return (((v = get(key)) != null) || containsKey(key))
? v
: defaultValue;
}
default void forEach(BiConsumer<? super K, ? super V> action) {
Objects.requireNonNull(action);
for (Map.Entry<K, V> entry : entrySet()) {
K k;
V v;
try {
k = entry.getKey();
v = entry.getValue();
} catch(IllegalStateException ise) {
throw new ConcurrentModificationException(ise);
}
action.accept(k, v);
}
}
default void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
Objects.requireNonNull(function);
for (Map.Entry<K, V> entry : entrySet()) {
K k;
V v;
try {
k = entry.getKey();
v = entry.getValue();
} catch(IllegalStateException ise) {
throw new ConcurrentModificationException(ise);
}
v = function.apply(k, v);
try {
entry.setValue(v);
} catch(IllegalStateException ise) {
throw new ConcurrentModificationException(ise);
}
}
}
default V putIfAbsent(K key, V value) {
V v = get(key);
if (v == null) {
v = put(key, value);
}
return v;
}
default boolean remove(Object key, Object value) {
Object curValue = get(key);
if (!Objects.equals(curValue, value) ||
(curValue == null && !containsKey(key))) {
return false;
}
remove(key);
return true;
}
default boolean replace(K key, V oldValue, V newValue) {
Object curValue = get(key);
if (!Objects.equals(curValue, oldValue) ||
(curValue == null && !containsKey(key))) {
return false;
}
put(key, newValue);
return true;
}
default V replace(K key, V value) {
V curValue;
if (((curValue = get(key)) != null) || containsKey(key)) {
curValue = put(key, value);
}
return curValue;
}
default V computeIfAbsent(K key,
Function<? super K, ? extends V> mappingFunction) {
Objects.requireNonNull(mappingFunction);
V v;
if ((v = get(key)) == null) {
V newValue;
if ((newValue = mappingFunction.apply(key)) != null) {
put(key, newValue);
return newValue;
}
}
return v;
}
default V computeIfPresent(K key,
BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
Objects.requireNonNull(remappingFunction);
V oldValue;
if ((oldValue = get(key)) != null) {
V newValue = remappingFunction.apply(key, oldValue);
if (newValue != null) {
put(key, newValue);
return newValue;
} else {
remove(key);
return null;
}
} else {
return null;
}
}
default V compute(K key,
BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
Objects.requireNonNull(remappingFunction);
V oldValue = get(key);
V newValue = remappingFunction.apply(key, oldValue);
if (newValue == null) {
if (oldValue != null || containsKey(key)) {
remove(key);
return null;
} else {
return null;
}
} else {
put(key, newValue);
return newValue;
}
}
default V merge(K key, V value,
BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
Objects.requireNonNull(remappingFunction);
Objects.requireNonNull(value);
V oldValue = get(key);
V newValue = (oldValue == null) ? value :
remappingFunction.apply(oldValue, value);
if(newValue == null) {
remove(key);
} else {
put(key, newValue);
}
return newValue;
}
}