Set集合有个重要的性质:元素不重复
Set是Collection的子接口,Collection是Iterable子接口
public interface Set<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 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();
default Spliterator<E> spliterator() {
return Spliterators.spliterator(this, 0);
}
}
同时继承Collection接口的parallelStream, removeIf, stream方法
父接口 : Collection, Iterable
子接口: NavigableSet, SortedSet
实现类: AbstractSet, ConcurrentHashMap.KeySetView, ConcurrentSkipListSet, CopyOnWriteArraySet, EnumSet, HashSet, JobStateReasons, LinkedHashSet, TreeSet
通过看源码,会发现Set接口中的方法在Collection中已经定义过,为什么还要在Set中重写父类方法。当然方法之上的注释是有差别的。
List、Set和Queue虽然都是Collection的子接口,但是他们的性质不同,比如说Set中的元素是不可重复的,通过重写父类方法,并且修改注释,可以更好的进行区分,使用时也更加清晰明确。同时Set接口下还有子接口,如果我们通过它的子接口查看父接口,发现其中没有任何方法,那还要再往上查找父接口。这种分层的设计,也使得集合接口的变更更加灵活,假设如果Collection接口哪天废弃了,List接口及其子接口依旧可以提供服务。
具体的Set性质参考https://docs.oracle.com/javase/8/docs/api/java/util/Set.html