JAVA——使用Arrays.asList()的注意事项(修改List会同步修改原数组)

目录

Arrays.asList()方法的官方文档介绍:

官方文档介绍的个人总结

对返回List的修改会同步修改原数组,反之亦然

对原数组修改会同步修改返回List

对返回List修改会同步修改原数组

原因(和内部实现Arrays有关)


Arrays.asList()方法的官方文档介绍:

Modifier and TypeMethod and Description
static <T> List<T>asList(T... a)

Returns a fixed-size list backed by the specified array.

  • asList

    @SafeVarargs
    public static <T> List<T> asList(T... a)
    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 Collection.toArray(). The returned list is serializable and implements RandomAccess.

    This method also provides a convenient way to create a fixed-size list initialized to contain several elements:

         List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
     

    Type Parameters:

    T - the class of the objects in the array

    Parameters:

    a - the array by which the list will be backed

    Returns:

    a list view of the specified array

官方文档介绍的个人总结

1、返回一个固定大小的list,为什么说是固定大小的?因为这个返回的list不支持add()、remove()、clear()等会修改list集合元素个数的方法(原因见通过Arrays.asList方法将数组转成集合后,能否修改集合个数? (juejin.cn)

2、既然返回的list不能修改元素个数,那么这个返回的list主要是起什么作用的?

This method acts as bridge between array-based and collection-based APIs

有些API是基于数组操作的,有些API是基于集合操作的,这个方法主要是为了将数组转化成集合以方便使用一些基于集合操作的API

同理,Collection.toArray()也是起到一个类似的作用,将集合转化为数组以方便使用一些基于数组操作的API

例子如下,翻转操作只存在于Collections类的方法中,为了反转words数组我们使用Arrays.asList将其转换为List集合

Collections.reverse(Arrays.asList(words));

对返回List的修改会同步修改原数组,反之亦然

对原数组修改会同步修改返回List

如果我们在使用asList的时候,对原始数组进行修改,那么会出现什么结果?

public static void main(String[] args) {
    
    String[] arr1 = {"1","2","3","4","5"};
    List list2 = Arrays.asList(arr1);
    System.out.println(list2);
    arr1[1] = "0";
    System.out.println(list2);
}



输出为:
[1, 2, 3, 4, 5]
[1, 0, 3, 4, 5]

可以看到,当我们使用asList之后,再对其原始的数组进行修改,那么之前被转换的List的值也会发生变化。如果我们把这个结果通过参数传递给其他线程,那么可能就会产生很多共享数据导致的奇怪问题。

对返回List修改会同步修改原数组

通过Arrays.asList方法将数组转成集合后,能否修改集合个数?针对这个问题,我们直接给出例子:

public class Demo {
    public static void main(String[] args){
        String[] strings={"A","B","C"};
        List<String> stringList=Arrays.asList(strings);

        stringList.set(0,"G");
        System.out.println(strings[0]);

        stringList.add("M");
    }
}
复制代码

运行结果:

G
Exception in thread "main" java.lang.UnsupportedOperationException
	at java.util.AbstractList.add(AbstractList.java:148)
	at java.util.AbstractList.add(AbstractList.java:108)
	...

原因(和内部实现Arrays有关)

通过Arrays.asList方法将数组转成集合后,能否修改集合个数? (juejin.cn)

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值