asList详解

本文深入解析了Java中Arrays.asList()方法的实现原理,指出该方法返回一个固定大小且不可修改的列表。文章强调了直接使用此方法可能带来的限制,并提供了如何创建可修改列表的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

asList(T... a)返回的是一个固定大小的list集合

源码分析:

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

此时的ArrayList为Arrays里面自定义的一个私有的内部类

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

其父类AbstractList中事务方法都被禁止了,使用时需要确保返回的list不会去修改。若需要修改可以修改为

 new ArrayList<>(Arrays.asList(T... a));
 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();
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值