Java踩坑之List的removeAll方法
最近在公司写东西,发现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>
- * List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
- * </pre>
- *
- * @param <T> the class of the objects in the array
- * @param a the array by which the list will be backed
- * @return a list view of the specified array
- */
- @SafeVarargs
- @SuppressWarnings("varargs")
- public static <T> List<T> asList(T... a) {
- return new ArrayList<>(a);
- }
- private static class ArrayList<E> extends AbstractList<E>
- implements RandomAccess, java.io.Serializable
- {
- private static final long serialVersionUID = -2764017481108945198L;
- private final E[] a;
- ArrayList(E[] array) {
- a = Objects.requireNonNull(array);
- }
- @Override
- public int size() {
- return a.length;
- }
- @Override
- public Object[] toArray() {
- return a.clone();
- }
- @Override
- @SuppressWarnings("unchecked")
- public <T> T[] toArray(T[] a) {
- int size = size();
- if (a.length < size)
- return Arrays.copyOf(this.a, size,
- (Class<? extends T[]>) a.getClass());
- System.arraycopy(this.a, 0, a, 0, size);
- if (a.length > size)
- a[size] = null;
- return a;
- }
- @Override
- public E get(int index) {
- return a[index];
- }
- @Override
- public E set(int index, E element) {
- E oldValue = a[index];
- a[index] = element;
- return oldValue;
- }
- @Override
- public int indexOf(Object o) {
- E[] a = this.a;
- if (o == null) {
- for (int i = 0; i < a.length; i++)
- if (a[i] == null)
- return i;
- } else {
- for (int i = 0; i < a.length; i++)
- if (o.equals(a[i]))
- return i;
- }
- return -1;
- }
- ...... //看的出来,这个list是可以修改的 但是要通过set方法
- }
所以调用removeAll方法的时候 会调用AbstractList的父类AbstractCollection的removeAll方法:
- public boolean removeAll(Collection<?> c) {
- Objects.requireNonNull(c);
- boolean modified = false;
- Iterator<?> it = iterator();
- while (it.hasNext()) {
- if (c.contains(it.next())) {
- it.remove();
- modified = true;
- }
- }
- return modified;
- }
ArrayList是数组 在循环的时候删除元素 一定会出现问题
002报错的原因是与001类似:Collections.singletonList的返回值SingletonSet也是自己的内部类
- /**
- * Returns an immutable list containing only the specified object. // 返回不可变的list
- * The returned list is serializable.
- *
- * @param <T> the class of the objects in the list
- * @param o the sole object to be stored in the returned list.
- * @return an immutable list containing only the specified object.
- * @since 1.3
- */
- public static <T> List<T> singletonList(T o) {
- return new SingletonList<>(o);
- }
- private static class SingletonList<E>
- extends AbstractList<E>
- implements RandomAccess, Serializable {
- private static final long serialVersionUID = 3093736618740652951L;
- private final E element;
- SingletonList(E obj) {element = obj;}
- public Iterator<E> iterator() {
- return singletonIterator(element);
- }
- public int size() {return 1;}
- public boolean contains(Object obj) {return eq(obj, element);}
- public E get(int index) {
- if (index != 0)
- throw new IndexOutOfBoundsException("Index: "+index+", Size: 1");
- return element;
- }
- // Override default methods for Collection
- @Override
- public void forEach(Consumer<? super E> action) {
- action.accept(element);
- }
- @Override
- public boolean removeIf(Predicate<? super E> filter) {
- throw new UnsupportedOperationException();
- }
- @Override
- public void replaceAll(UnaryOperator<E> operator) {
- throw new UnsupportedOperationException();
- }
- @Override
- public void sort(Comparator<? super E> c) {
- }
- @Override
- public Spliterator<E> spliterator() {
- return singletonSpliterator(element);
- }
- }
- // 可以看出 这个list是一个只读的list 并未对外提供编辑方法
同样会调用AbstractCollection的removeAll方法
003是我new的ArrayList对象,会调用自己内部重写的removeAll方法,针对数组重写了删除方法,不会出问题,解决001、002的问题 最简单的办法可以用new ArrayList()包一层就ok了!
究其原因还是自己对源码的研究不足!
更多技术资源请访问:https://www.zhaochao.top/articles
Java踩坑之List的removeAll方法的更多相关文章
- java踩坑记
1.String 相等 稍微有点经验的程序员都会用equals比较而不是用 ==,但用equals就真的安全了吗,看下面的代码 user.getName().equals("xiaoming ...
- 『OGG 02』Win7 配置 Oracle GoldenGate Adapter Java 踩坑指南
上一文章 <__Win7 配置OGG(Oracle GoldenGate).docx>定下了 两个目标: 目标1: 给安装的Oracle_11g 创建 两个用户 admin 和 root ...
- Java踩坑之路
陆陆续续学Java也快一年多了,从开始的一窍不通到现在的初窥门径,我努力过,迷茫过,痛过,乐过,反思过,沉淀过.趁着新年,我希望能把这些东西记下来,就当是我一路走来的脚印. 一.初识网站应用 记得第一 ...
- JAVA踩坑录
以前踩了很多坑,大多忘了.现在踩了坑,想起了一定记下来. 1. 字符串分割,这种工具类,首次使用一定要先看一眼,不然跳坑 commons-lang StringUtils.split分割时会去掉空串: ...
- java踩坑
1. java判断两个字符串是否相等用equals 2. java只传递指针遇到的坑: 1 import java.util.*; 2 3 public class mapTest { 4 publi ...
- Java踩坑记系列之Arrays.AsList
java.util.Arrays的asList方法可以方便的将数组转化为集合,我们平时开发在初始化ArrayList时使用的比较多,可以简化代码,但这个静态方法asList()有几个坑需要注意: 一. ...
- mongo java 踩坑记
为什么会有这么多坑 1. Java会把 id:String = "合法ObjectId" 好心好意的 转为 _id:ObjectId 类型. 2. 为了避免第1点, 我定义了 ...
- Spark SQL 用户自定义函数UDF、用户自定义聚合函数UDAF 教程(Java踩坑教学版)
在Spark中,也支持Hive中的自定义函数.自定义函数大致可以分为三种: UDF(User-Defined-Function),即最基本的自定义函数,类似to_char,to_date等 UDAF( ...
- Android踩坑随笔Fragment中onActivityResult方法不被调用
最近项目里要做头像功能,参考了这篇博客(GitHub - zhudfly/SelectAvatarApplication: 一个选择并显示头像圆形控件,可以通过拍照或者选择相册中的图片来设置图片),但 ...
随机推荐
- 鸿蒙内核源码分析(位图管理篇) | 谁能一分钱分两半用 | 百篇博客分析OpenHarmony源码 | v19.03
百篇博客系列篇.本篇为: v19.xx 鸿蒙内核源码分析(位图管理篇) | 谁能一分钱分两半用 | 51.c.h .o 先看四个宏定义,进程和线程(线程就是任务)最高和最低优先级定义,[0,31]区间 ...
- P4457-[BJOI2018]治疗之雨【期望dp,高斯消元】
正题 题目链接:https://www.luogu.com.cn/problem/P4457 题目大意 开始一个人最大生命值为\(n\),剩余\(hp\)点生命,然后每个时刻如果生命值没有满那么有\( ...
- WPF进阶技巧和实战07--自定义元素02
在01节中,研究了如何开发自定义控件,下节开始考虑更特殊的选择:派生自定义面板以及构建自定义绘图 创建自定义面板 创建自定义面板是一种比较常见的自定义控件开发子集,面板可以驻留一个或多个子元素,并且实 ...
- Spring Boot 整合单机websocket(附github源码)
websocket 概念 websocket 是一个通信协议,通过单个 TCP 连接提供全双工通信.websocket 连接成功后,服务端和客户可以进行双向通信.不同于 http 通信协议需要每次由客 ...
- The Data Way Vol.4|开源是创造软件诸多方法中最好的一种形式
关于「The Data Way」 「The Data Way」是由 SphereEx 公司出品的一档播客节目.这里有开源.数据.技术的故事,同时我们关注开发者的工作日常,也讨论开发者的生活日常:我们聚 ...
- GoLang设计模式10 - 中介者模式
中介者模式是一种行为型设计模式.在中介者模式中创建了一个中介对象来负责不同类间的通信.因为这些类不需要直接交互,所以也就能避免它们之间的直接依赖,实现解耦的效果. 中介者模式的一个典型案例是老式小火车 ...
- 纯前端H5小应用_localStorage存储
开发缘由[需求发现和分析] 想要送朋友一个礼物,但是想了想,街上买的东西,em~,我们这样的猿确实不会选礼物啊,由此就想利用自己手中的工具和知识做点有用的东西吧,抱枕是礼物,钢笔是礼物,电子产品也是礼 ...
- Redis大集群扩容性能优化实践
一.背景 在现网环境,一些使用Redis集群的业务随着业务量的上涨,往往需要进行节点扩容操作. 之前有了解到运维同学对一些节点数比较大的Redis集群进行扩容操作后,业务侧反映集群性能下降,具体表现在 ...
- Python 面向对象笔记
Python 面向对象课程笔记 前言 Python 面向对象 正文 基本概念 什么是对象: 万物皆对象 对象是具体物体: 拥有属性 拥有行为 封装零散为整体 OOP(Object Oriented P ...
- pycharm安装第三方库
https://jingyan.baidu.com/article/4853e1e54b845e1909f7268f.html