转载请标明出处^_^
原文首发于: www.zhangruibin.com
本文出自于: RebornChang的博客
ArrayList
ArrayList中的removeIf
ArrayList 继承了 AbstractList,实现了 List、 RandomAccess、 Cloneable、java.io.Serializable接口;
AbstractList继承了 AbstractCollection,实现了 List接口;
AbstractCollection实现了Collection接口;
Collection接口继承了Iterable接口;
Collection为顶级集合接口,实现了Iterable接口,可以迭代。
Collction接口中在Jdk1.8之后新增了个removeIf,有啥用?
removeIf源码@since 1.8:
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;
}
ArrayList对其进行重写:
@Override
public boolean removeIf(Predicate<? super E> filter) {
//首先要验证规则不能为空
Objects.requireNonNull(filter);
// figure out which elements are to be removed
// any exception thrown from the filter predicate at this stage
// will leave the collection unmodified
//计数器,记录revove掉的次数
int removeCount = 0;
//声明要rem