stream().toList()
下面这两行代码相同吗?
ini
List<Integer> list1 = list.stream().toList();
List<Integer> list2 = list.stream().collect(Collectors.toList());
在Idea里,Idea还会提醒你可以替换,难道真的是相同的api吗?
我们直接打印一下它们的Class
Java
List<Integer> list1 = list.stream().toList();
List<Integer> list2 = list.stream().collect(Collectors.toList());
System.out.println(list1.getClass());
System.out.println(list2.getClass());
kotlin
class java.util.ImmutableCollections$ListN
class java.util.ArrayList
发现一个是ImmutableCollection,一个是ArrayList
从名字中就可以看出来list1是不可变的,remove一下果然抛出了异常
Java
// 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(); }