最近看到《Java核心技术 卷Ⅰ》集合的部分,知道这是很重要的一部分内容,特地学习一下集合的源码。本来是想在CSDN上面写的,但是CSDN社区的环境太乱了,恰好在掘金上看到了“大大纸飞机”同学写的集合相关的文章很不错。所以转战掘金。
Java集合框架包含了很多的数据结构,主要包括 List列表、Set集合、Map映射、迭代器(Iterator、Enumeration)、工具类(Arrays、Collections)几个部分。
集合框架的接口
画图使用了:processon.com
其中有两个最基本的接口:Collection和Map。 而List、Set和Queue接口又继承了Collection接口。SortedMap接口继承了Map接口。(1)Collection接口public interface Collection<E> extends Iterable<E>
Collection接口包含了我们平时使用的一些方法:
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);
复制代码
(2)List接口
List是一个继承自Collection的接口,List是集合中的一种。List是有序的队列,List中的每一个元素都有一个索引;第一个元素的索引值是0,往后的元素的索引值依次+1。和Set不同,List中允许有重复的元素。
(3)Set接口
Set接口也是集合中的一种。Set的add方法不允许增加重复的元素。可以适当的定义equals方法:只要两个集包含同样的元素就认为是相等的,而不要求这些元素有同样的顺序。hashCode方法的定义要保证包含相同元素的两个集会得到相同的散列码。
SortedSet会提供用于排序的比较器对象。
public interface Set<E> extends Collection<E>{
int size();
boolean isEmpty();
boolean contains(Object o);
Iterator<E> iterator();//迭代器对象
@Override
default Spliterator<E> spliterator() {
return Spliterators.spliterator(this, Spliterator.DISTINCT);//并行遍历的迭代器
}
}
复制代码
(4)Queue接口
Queue接口也继承自Collection接口,实现了队列的数据结构:
boolean add(E e);//增加一个元索
boolean offer(E e);//添加一个元素并返回true,如果队列已满,则返回false
E remove();//移除并返回队列头部的元,如果队列为空,则抛出一个NoSuchElementException异常
E poll();//移除并返问队列头部的元素,如果队列为空,则返回null
E element();//返回队列头部的元素,如果队列为空,则抛出一个NoSuchElementException异常
E peek();//返回队列头部的元素,如果队列为空,则返回null
复制代码
(5)Iterator接口
Iterator集合的迭代器。集合可以通过Iterator去遍历集合中的元素。Iterator提供的API接口,包括:是否存在下一个元素、获取下一个元素、删除当前元素。
boolean hasNext();
E next();
default void remove() {
throw new UnsupportedOperationException("remove");
}
default void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
while (hasNext())
action.accept(next());
}
复制代码
(6)Map接口
提供了映射需要的基本方法:
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();
复制代码
(7)SortedMap接口
SortedMap与SortedSet接口会提供用于排序的比较器对象。
public interface SortedMap<K,V> extends Map<K,V>{
Comparator<? super K> comparator();
SortedMap<K,V> subMap(K fromKey, K toKey);
SortedMap<K,V> headMap(K toKey);
SortedMap<K,V> tailMap(K fromKey);
K firstKey();
K lastKey();
Set<K> keySet();
Collection<V> values();
Set<Map.Entry<K, V>> entrySet();
}
复制代码
(8)Iterator接口
public interface Iterator<E> {
boolean hasNext();
E next();
default void remove() {
throw new UnsupportedOperationException("remove");
}
//主要将每个元素作为参数发给action来执行特定操作
default void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
while (hasNext())
action.accept(next());
}
}
复制代码