asList转换为集合
来源:互联网 发布:中国梦之队服装淘宝网 编辑:程序博客网 时间:2024/05/17 13:40
java中我们经常会使用Arrays.asList(数组);将数组转换为List类型,但是却不能对转换后的List进行增删。示例如下:
- import java.util.*;
- class ArraysDemo
- {
- public static void main(String[] args)
- {
- // 定义一个Sting型数组
- String[] arr={"abc","abcde","desf","dfdf","fdfee"};
- // 将数组转换为List集合
- List<String> list=Arrays.asList(arr);
- // 获取第一元素的值
- System.out.println(list.get(1));
- // 增加元素
- list.add("test");
- }
- }
运行结果:
- abcde
- Exception in thread "main" java.lang.UnsupportedOperationException
- at java.util.AbstractList.add(Unknown Source)
- at java.util.AbstractList.add(Unknown Source)
- at ArraysDemo.main(ArraysDemo.java:13)<pre name="code" class="java">
运行结果报出了UnsuportedOperationException,查阅如下Arrays.asList()方法源码可以得知,
Arrays内部实现了私有内部静态类,而且没有实现增删的方法。所以通过asList()生成的List没有增删方法。
- @SafeVarargs
- public static <T> List<T> asList(T... a) {
- return new ArrayList<>(a);
- }
- /**
- * @serial include
- */
- //定义私有内部静态类,继承了AbstractList虚类
- 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) {
- if (array==null)
- throw new NullPointerException();
- a = array;
- }
- public int size() {
- return a.length;
- }
- public Object[] toArray() {
- return a.clone();
- }
- 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;
- }
- public E get(int index) {
- return a[index];
- }
- public E set(int index, E element) {
- E oldValue = a[index];
- a[index] = element;
- return oldValue;
- }
- public int indexOf(Object o) {
- 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;
- }
- public boolean contains(Object o) {
- return indexOf(o) != -1;
- }
- }
阅读全文
0 0
- asList转换为集合
- Arrays.asList转换数组为集合List对象
- 数组转换成集合中的Arrays.asList用法
- 数组转换成集合中的Arrays.asList用法
- 集合转换为数组
- Arrays.asList返回的集合
- Java集合 asList的缺陷
- 数组转换为List(Arrays.asList)后add或remove出现UnsupportedOperationException
- 数组转换为List(Arrays.asList)后add或remove出现UnsupportedOperationException
- Arrays.asList(strArray)转换为List,执行remove(),报异常:java.lang.UnsupportedOperationException深究
- asList的使用缺陷—不能将8种基本数据类型数组转换为列表
- 数组转换为List(Arrays.asList)后add或remove出现UnsupportedOperationException
- List集合转换为数组
- 集合转换为Json数组
- 将一个集合转换为一个DataTable
- DataTable类型对象转换为List集合
- CollectionUtils 转换数组为集合对象
- 将List 集合 转换为Jsion 数据
- 归并排序
- SDOI2015 序列统计 NTT+原根+快速幂
- 词法分析器 c语言
- QTableWidget,QTableView分页(2)——使用分页栏
- input 不可填写
- asList转换为集合
- PHP建设银行支付网络回调验签
- javascript深入理解js闭包
- WWDC 2017 Session笔记
- 51nod 1799 思维 二分 数论 分块打表
- POJ--3259--spfa spfa写法
- pig入门
- shell脚本编程
- centos 安装 redis3.0.0 集群