UnsupportedOperationException 异常

此代码运行出现 UnsupportedOperationException

	public static void main(String[] args) {
		Integer[] datas = {1,2,3,4,5};
		List<Integer> list = Arrays.asList(datas);
		list.add(5);
		System.out.println(list.size());
	}

看下源码找原因:Arrays类中asList()方法
可以看出 这是个固定size的list

 /**
     * Returns a fixed-size list backed by the specified array.  (Changes to
     * 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&lt;String&gt; stooges = Arrays.asList("Larry", "Moe", "Curly");

     *
     * @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
     */

 public static <T> List<T> asList(T... a) {
        return new ArrayList<>(a);
    }

ArrayList<>还是在Arrays类中属于私有内部类,该类继承抽象AbstractiList重写了很多方法但是没有add

private static class ArrayList<E> extends AbstractList<E>
        implements RandomAccess, java.io.Serializable

继续看AbstractList
发现可变容量的list需要重写add方法

 * <p>To implement a modifiable list, the programmer must additionally
 * override the {@link #set(int, Object) set(int, E)} method (which otherwise
 * throws an {@code UnsupportedOperationException}).  If the list is
 * variable-size the programmer must additionally override the
 * {@link #add(int, Object) add(int, E)} and {@link #remove(int)} methods.

总结:Arrays工具类里的asList是数组和集合的桥梁,但不能直接进行元素添加
若需使用需要增加自动扩容的功能,可以参考如下例子


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Vanas
 * @create 2020-03-21 9:50 下午
 */
public class Test {

    public static void main(String[] args) {
        Integer[] datas = {1, 2, 3, 4, 5};
        List<Integer> list = Arrays.asList(datas);//固
        List list1 = new ArrayList<>(list);
//        list.add(5);
        /*
        java.lang.UnsupportedOperationException
         */
        list1.add(5);
        System.out.println(list1.size());
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值