Arrays.asList()返回只读的List

List<Integer> list = Arrays.asList(1, 2, 3);

list.clear(); // throws java.lang.UnsupportedOperationException

对Arrays.asList()转化的List是一个固定长度的List,不支持add() remove() clear()等操作


Arrays.asList()返回的是一个ArrayList对象

@SafeVarargs
@SuppressWarnings( "varargs")
public  static <T> List<T> asList(T... a) {
    return  new ArrayList<>(a);
}
而这个类继承自AbstractList类

AbstractList中而这个类中实现的所有对list的数据编辑操作都会抛出UnsupportedOperationException异常

/**
    * {@inheritDoc}
    *
    * <p>This implementation always throws an
    * {@code UnsupportedOperationException}.
    *
    * @throws UnsupportedOperationException {@inheritDoc}
    * @throws ClassCastException            {@inheritDoc}
    * @throws NullPointerException          {@inheritDoc}
    * @throws IllegalArgumentException      {@inheritDoc}
    * @throws IndexOutOfBoundsException     {@inheritDoc}
    */
    public E set( int index, E element) {
        throw  new UnsupportedOperationException();
   }

     /**
    * {@inheritDoc}
    *
    * <p>This implementation always throws an
    * {@code UnsupportedOperationException}.
    *
    * @throws UnsupportedOperationException {@inheritDoc}
    * @throws ClassCastException            {@inheritDoc}
    * @throws NullPointerException          {@inheritDoc}
    * @throws IllegalArgumentException      {@inheritDoc}
    * @throws IndexOutOfBoundsException     {@inheritDoc}
    */
    public  void add( int index, E element) {
        throw  new UnsupportedOperationException();
   }

/**
    * {@inheritDoc}
    *
    * <p>This implementation always throws an
    * {@code UnsupportedOperationException}.
    *
    * @throws UnsupportedOperationException {@inheritDoc}
    * @throws IndexOutOfBoundsException     {@inheritDoc}
    */
    public E remove( int index) {
        throw  new UnsupportedOperationException();
   }

所以Arrays.asList()返回的list是只读的并不能对list的数据进行相关修改!

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值