最近在公司写东西,发现List的removeAll方法报错 Demo代码如下:
List<Long> ids1 = Arrays.asList(1L, 3L, 2L);
List<Long> ids2 = Collections.singletonList(2L);
List<Long> ids3 = new ArrayList<>();
ids3.add(1L);
ids3.add(2L);
List<Long> ids = new ArrayList<>();
ids.add(2L);
System.out.println("==== 001");
ids1.removeAll(ids); // 这一步会报错
System.out.println("==== 002");
ids2.removeAll(ids); // 这一步也会报错
System.out.println("==== 003");
ids3.removeAll(ids);
001报错的原因是:Arrays.asList 返回的List是自己内部实现的ArrayList 而不是util下的ArrayList对象
/**
* Returns a fixed-size list backed by the specified array. (Changes to //明确指出 返回的是固定大小的list
* the returned list "write through" to the array.) This method acts
* as bridge between array-based and collection-based APIs, in
* combination with {@link Collection#toArray}. The returned list is
* serializable and implements {@link RandomAccess}.
*
* <p>This method also provides a convenient way to create a fixed-size
* list initialized to contain several elements:
* <pre>