当前位置: 首页 > news >正文

Arrays.asList() add方法报错java.lang.UnsupportedOperationException

1. 问题说明

记录一下遇到的这个bug,下面是段个简化后的问题重现代码。

public class Test {public static void main(String[] args) {List<Integer> list = Arrays.asList(1, 2, 3);list.add(4);}
}

在这里插入图片描述

2. 原因分析

我们看一下Arrays.asList(…) 的源码:

/*
- Returns a fixed-size list backed by the specified array. Changes made to the array will be visible in the returned list, and changes made to the list will be visible in the array. The returned list is Serializable and implements RandomAccess.
- The returned list implements the optional Collection methods, except those that would change the size of the returned list. Those methods leave the list unchanged and throw UnsupportedOperationException.
- If the specified array's actual component type differs from the type parameter T, this can result in operations on the returned list throwing an ArrayStoreException.
*/
@SafeVarargs
/varargs/
public static <T> List<T> asList(T... a) {return new ArrayList<>(a);
}
//  上面的 return new ArrayList<>(a)中的ArrayList源码
private static class ArrayList<E> extends AbstractList<E> implements RandomAccess, java.io.Serializable { // ... 
}

从方法上给出的注释信息中的第2条可以知道,返回的其实是 java.util.Arrays$ArrayList(也就是一个内部类,并不是 java.util.ArrayList)。它内部基于数组实现,只能固定大小,不支持 add()addAll()remove() 等结构性操作 。如果如果你需要一个可变、可以添加或删除元素的列表,请用:

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3));
list.add(3); // 安全可行

3. 补充说明

  • 在高并发或多线程环境下,如果基础数组发生变化,Arrays.asList 返回的列表内容也会变化,可能引发数据不一致。
  • List.of(...)(Java 9+)是完全不可变的列表,任何变结构操作都会立即抛异常;而 Arrays.asList 是“可修改元素但不可改大小”。
    在这里插入图片描述
http://www.lryc.cn/news/608677.html

相关文章:

  • Apache Shenyu 本地启动及快速入门
  • 【abc417】E - A Path in A Dictionary
  • HTTPS的概念和工作过程
  • Kazam产生.movie.mux后恢复视频为.mp4
  • Transformer模型用于MT信号相关性预测与分析
  • 知识蒸馏 - 基于KL散度的知识蒸馏 HelloWorld 示例 采用PyTorch 内置函数F.kl_div的实现方式
  • 【C++】封装,this指针
  • 个人自用----c语言指针复习(malloc)
  • 大语言模型涉及的一些概念(持续更新)
  • 安卓加固脱壳
  • 1.8 axios详解
  • Axios介绍
  • 超声波泄露传感器
  • SpringBoot3.x入门到精通系列:2.6 整合 Redis 详解
  • Python 基础语法(一):从常量到运算符
  • jvm之jconsole的使用
  • MySQL连接算法和小表驱动大表的原理
  • 初识prometheus
  • Selenium Web 自动化
  • 【软考中级网络工程师】知识点之 RIP 协议
  • 华为智能家居与Spring人工智能
  • 决策树学习全解析:从理论到实战
  • C++手撕基于ID3算法的决策树
  • 著作权登记遇难题:创作者如何突破确权困境?
  • 自动驾驶中的传感器技术19——Camera(10)
  • ELECTRICAL靶场
  • ClickHouse Windows迁移方案与测试
  • 【动态规划算法】路径问题
  • WebRTC前处理模块技术详解:音频3A处理与视频优化实践
  • Node.js (Express) + MySQL + Redis构建项目流程