JDK1.8 ArrayList源码剖析(二)
程序员文章站
2022-03-03 23:06:13
...
JDK1.8中新增的特性:
1. void forEach(Consumer<? super E> action)
:JDK8中新特性,对list中每个元素分别进行操作,如:
ArrayList<Integer> al = new ArrayList<>();
al.add(0);
al.add(1);
al.add(2);
al.add(3);
al.forEach(line -> System.out.println(line));
2.Spliterator<E> spliterator()
:返回一个并行迭代器
return new ArrayListSpliterator<>(this, 0, -1, 0);
示例如下:
ArrayList<String> a1 = new ArrayList<String>();
a1.add("asd");
a1.add("zxc");
a1.add("xfgj");
a1.add("asd");
Spliterator<String> spliterator = a1.spliterator();
spliterator.forEachRemaining(ele -> System.out.print(ele + " "));
结果如下:
asd zxc xfgj asd
3.boolean removeIf(Predicate<? super E> filter)
:移除集合中满足给定条件的所有元素。filter是令元素移除成功的条件过滤器,示例如下:
ArrayList<String> a1 = new ArrayList<String>();
a1.add("asd");
a1.add("zxc");
a1.add("xfgj");
a1.add("adsw");
a1.forEach(element -> System.out.print(element + " "));
System.out.println();
a1.removeIf(element -> element.startsWith("a"));// 过滤掉以"a"开头的元素
a1.forEach(element -> System.out.print(element + " "));
System.out.println();
Predicate<String> predicate = (element) -> element.contains("j"); // 这里单独定义了过滤器
a1.removeIf(predicate); // 过滤掉包含"j"的元素
a1.forEach(line -> System.out.println(line)); // 输出 zxc
4.void replaceAll(UnaryOperator<E> operator)
:替换list中的元素
Objects.requireNonNull(operator);
final int expectedModCount = modCount;
final int size = this.size;
for (int i=0; modCount == expectedModCount && i < size; i++) {
elementData[i] = operator.apply((E) elementData[i]);
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
示例如下:
ArrayList<String> a1 = new ArrayList<String>();
a1.add("asd");
a1.add("zxc");
a1.add("xfgj");
a1.add("asd");
a1.replaceAll(element -> element.contains("a")?"111": "000");
a1.forEach(elemet -> System.out.print(elemet + " "));
输出结果如下:
111 000 000 111
5.void sort(Comparator<? super E> c)
:用于list集合排序,使用了Comparator比较器来比较,实现里面的compare方法,compareTo比较之后,返回的参数是int类型,0则表示相等,1表示大于,-1负数则表示小于。
@Override
@SuppressWarnings("unchecked")
public void sort(Comparator<? super E> c) {
final int expectedModCount = modCount;
Arrays.sort((E[]) elementData, 0, size, c);
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}
示例如下:
ArrayList<String> a1 = new ArrayList<String>();
a1.add("asd");
a1.add("zxc");
a1.add("xfgj");
a1.add("adsw");
a1.sort(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
a1.forEach(line -> System.out.print(line + " "));