Arrays.asList()怀疑? [英] Arrays.asList() doubt?

查看:111
本文介绍了Arrays.asList()怀疑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

人们说, asList 方法将数组转换为列表而不复制,因此'aList'中的每个更改都将反映为'a'。因此,在'aList'中添加新值是非法的,因为数组具有固定大小。

People say that asList method convert the array into list and its not copying, so every change in 'aList' will reflect into 'a'. So add new values in 'aList' is illegal, since array have fixed size.

但是, asList()方法返回 ArrayList< T> 。编译器如何区分第3行和第5行。第3行给出了异常( UnsupportedOperationException )。

But, asList() method returns ArrayList<T>. How the compiler differentiates line 3 from 5. Line 3 gives me exception (UnsupportedOperationException).

        String[] a = {"a","b","c","d"};//1
        List<String> aList =  Arrays.asList(a);//2
        aList.add("e");//3
        List<String> b = new ArrayList<String>();//4
        b.add("a");//5

$ b b

推荐答案

Arrays.asList 接收的此List实现是数组上的一个特殊视图 - 不改变它的大小。

This List implementation you receive from Arrays.asList is a special view on the array - you can't change it's size.

Arrays.asList()的返回类型为 java.util.Arrays。 ArrayList ,它经常与 java.util.ArrayList 混淆。 Arrays.ArrayList 只是将数组显示为列表

The return type of Arrays.asList() is java.util.Arrays.ArrayList which is often confused with java.util.ArrayList. Arrays.ArrayList simply shows the array as a list.

这篇关于Arrays.asList()怀疑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆