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();
    }

 

### Java `ArrayList.asList` 方法详解 #### 基本概念 `asList` 是 `java.util.Arrays` 类中的静态方法,用于将指定的数组转换为固定大小的列表。此列表由 `Arrays$ArrayList` 实现,不是 `java.util.ArrayList`。因此,在使用上存在一些差异[^1]。 #### 使用场景与注意事项 当调用 `Arrays.asList()` 返回的结果尝试执行诸如添加或移除元素的操作时会抛出 `UnsupportedOperationException` 异常,因为默认情况下返回的是一个不可修改的集合视图[^2]。如果确实需要对列表进行增删改查,则应该考虑创建一个新的 `ArrayList` 对象来包裹这个固定的列表实例[^3]。 #### 示例代码展示 下面展示了如何正确地利用 `Arrays.asList()` 并对其进行扩展以允许后续更改: ```java // 定义字符串数组并转成列表形式 String[] fruits = {"Apple", "Banana", "Cherry"}; List<String> fruitList = Arrays.asList(fruits); // 尝试直接向fruitList中增加新项将会失败(UnsupportedOperationException) // 正确做法是先将其转化为真正的ArrayList再做改动 List<String> modifiableFruitList = new ArrayList<>(fruitList); modifiableFruitList.add("Date"); System.out.println(modifiableFruitList); // 输出: [Apple, Banana, Cherry, Date] ``` 对于基本数据类型(如 int),应特别注意不要直接应用 `Arrays.asList()`,因为它不会按预期工作;而是应当采用包装类(如 Integer)或者通过流的方式处理[^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值