Java集合
集合
我这次不讲解用法,要知道怎么用,去翻阅 API 文档就好了,我这里,就稍微品尝一下集合的源码
这里,我先放上集合的所有继承关系图:
————单值存储————
Collection
下面就是 Collection 的源码,所有集合,都要实现 Collection接口
在早期,都是用 Collection 去指向集合实现的,但是因为无法区分 List 和 Set (主要是有取消重复元素的需要),所以,Sun 在开源项目 PetShop 中,开始推荐使用 List 和 Set 来指向集合的实现
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);
// Modification Operations
//增加元素
boolean add(E e);
//删除指定元素
boolean remove(Object o);
// Bulk Operations
//判断当前集合是否包含传入集合的所有元素
boolean containsAll(Collection<?> c);
//将传入集合的所有元素,放入当前集合
boolean addAll(Collection<? extends E> c);
boolean removeAll(Collection<?> c);
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;
}
//和传入的集合,取交集
boolean retainAll(Collection<?> c);
void clear();
// Comparison and hashing
boolean equals(Object o);
int hashCode();
@Override
default Spliterator<E> spliterator() {
return Spliterators.spliterator(this, 0);
}
//java8新增的 stream 流操作
default Stream<E> stream() {
return StreamSupport.stream(spliterator(), false);
}
default Stream<E> parallelStream() {
return StreamSupport.stream(spliterator(), true);
}
}
源码的注释中,还给出了 Collection 的所有子类:
* @see Set
* @see List
* @see Map
* @see SortedSet
* @see SortedMap
* @see HashSet
* @see TreeSet
* @see ArrayList
* @see LinkedList
* @see Vector
* @see Collections
* @see Arrays
* @see AbstractCollection
List
继承 Collection 接口,也添加了自己特殊的接口方法
public interface List<E> extends Collection<E> {
//...
}
相对于 Collection,添加的方法
ArrayList
这里,我们就小尝一下 ArrayList 的源码
ArrayList 在未被指定大小的时候,会默认申请一个长度为 10 的空间
如果在 add 的时候,长度不够,会扩容 1.5 倍
ArrayList,是线程不安全的,所以效率比 Vector 高(Vector 线程安全)