Java集合框架
上图从菜鸟教程上截取。
从图中可以看出,Java 集合框架主要包括两种类型的容器,一种是集合(Collection),存储一个元素集合,另一种是图(Map),存储键/值对映射。Collection 接口又有 3 种子类型,List、Set 和 Queue,再下面是一些抽象类,最后是具体实现类,常用的有 ArrayList、LinkedList、HashSet、LinkedHashSet、HashMap、LinkedHashMap 等等。
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);
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();
boolean equals(Object o);
int hashCode();
// Spliterator Stream java1.8新特性
// 可以并行遍历数据源
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);
}
}
面试题 比较Collection和Collections
Collection是Java集合框架的根级接口。Java集合框架中的大多数类都继承自此接口。List,Set和Queue是该接口的主要子接口。JDK不提供此接口的任何直接实现。但是,JDK提供了它的子接口的直接实现。ArrayList,Vector,HashSet,LinkedHashSet,PriorityQueue是Collection接口的一些间接实现。
Collections是java.util包中的实用程序类。它仅包含用于对Collection类型的对象进行操作的静态方法。例如,它具有查找集合中的最大元素的方法,对集合进行排序的方法,搜索集合中的特定元素的方法等等。