stream().toList()的大坑,你真的了解吗
stream().toList()
下面这两行代码相同吗?
List<Integer> list1 = list.stream().toList();
List<Integer> list2 = list.stream().collect(Collectors.toList());
在Idea里,Idea还会提醒你可以替换,难道真的是相同的api吗?
我们直接打印一下它们的Class
List<Integer> list1 = list.stream().toList();
List<Integer> list2 = list.stream().collect(Collectors.toList());
System.out.println(list1.getClass());
System.out.println(list2.getClass());
class java.util.ImmutableCollections$ListN
class java.util.ArrayList
发现一个是ImmutableCollection,一个是ArrayList
从名字中就可以看出来list1是不可变的,remove一下果然抛出了异常
// all mutating methods throw UnsupportedOperationException
@Override public void add(int index, E element) { throw uoe(); }
@Override public boolean addAll(int index, Collection<? extends E> c) { throw uoe(); }
@Override public E remove(int index) { throw uoe(); }
@Override public void replaceAll(UnaryOperator<E> operator) { throw uoe(); }
@Override public E set(int index, E element) { throw uoe(); }
@Override public void sort(Comparator<? super E> c) { throw uoe(); }
作者:湫qiu
来源:juejin.cn/post/7436938110023958565
来源:juejin.cn/post/7436938110023958565