Java集合里面的retainAll

java集合
为什么这样造的集合可以用retainAll()

img


这样的会报错

img

asList返回的对象是Arrays的一个内部类,并没有实现集合修改,因此调用其add/remove/clear等方法是会报错的。Arrays.asList体现的是适配器模式,其后台数据仍是数组(引用自参考链接),而retainAll应该是会调用其remove的方法,所以会报错(个人理解),可以通过java8新特性的stream流来解决(引用自参考链接),测试代码如下:
参考链接:
Exception in thread “main“ java.lang.UnsupportedOperationException_但求上进的博客-CSDN博客

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Collectors;

public class CollectionretailAllTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //test3();
        
        test4();
    }

    public static void test3() {
        Collection coll = new ArrayList();
        coll.add(3);
        coll.add("new");
        Collection coll1 = Arrays.asList(3,5,8);
        
        System.out.println("交集是:");
        coll.retainAll(coll1);
        System.out.println(coll);
        
    }
    public static void test4() {
        
        Object[] array = new Object[] {1,2,3,4};
        
        Collection coll =  Arrays.stream(array).collect(Collectors.toList());
        
        //Collection coll = Arrays.asList(1,2,3,4);
        Collection coll1 = Arrays.asList(3,5,8);
        
        System.out.println("交集是:");
        coll.retainAll(coll1);
        System.out.println(coll);
        
    }
}

img