当前位置:网站首页>UnsupportedOperationException异常
UnsupportedOperationException异常
2022-07-06 08:40:00 【头顶凉凉先生丶】
我们先来重温一下题目,有什么疑问的可以移步传送门。String[]和List< String >的区别及相互转换
public class test {
public static void main(String[] args) {
//定义一个字符长度为5的字符串
String[] strings = new String[5];
strings[0] = "a";
strings[1] = "b";
strings[2] = "c";
strings[3] = "d";
strings[4] = "e";
//调用Arrays中的asList方法将String[]转化为List<String>
List<String> list = Arrays.asList(strings);
System.out.println("list<String>:"+list.toString());
//为list添加一个元素
list.add("f");
System.out.println("list<String>:"+list.toString());
}
}
当当当,小可爱们是不是跟偶想的一样呢,这没问题啊,这不挺好的吗,先将String[]转换为List< String >,然后再添加一个元素f,那最终输出的结果是a,b,c,d,e,f。
这套逻辑简直完美,此处配上祖蓝的perfect。

呵呵呵,还是太年轻,如果是这样,偶还说什么,这不没话说了吗(摊手)。
好了,话不多说,咱直接看结果。
duang,傻眼了,咦,这是个啥啊,为啥报错啦,这不符合逻辑啊。偶是不是又变菜啦,nonono,我是要成为大鸟的女纸。
下面开始正式讲解了,不闹啦。
- 咱先看再String[]转为List< String >的时候没有报错,是正确的输出了结果。那是在对List进行add操作的时候,报错啦。emmm,在哪行出错找到了。
- 那么下面就找一下,他为什么报错。我们看一下进行转化的时候,都干了啥,如下图,asList是通过新建一个ArrayList来接收String[]的数值。

- 再看ArrayList是不是我们熟悉的那个ArrayList,也就是可以通过add,remove方法进行操作,如下图,很明显,这并不是ArrayList类,而是Arrays里面新建了一个内部类ArrayList,而这个内部类是继承于AbstractList类,AbstractList类里面的add方法是会抛出UnsupportedOperationException异常的。



- 那么有人要问,咦,那为什么ArrayList可以呢,答案就是ArrayList给我们做好了事情,也就是重写了add方法。
综上所论,如果在将String[]转化为List< String >的时候,是不能对转化出来的结果进行add,remove操作的,因为他们并不是我们熟悉的ArrayList,而是Arrays里面的内部类ArrayList。
边栏推荐
猜你喜欢

FairGuard游戏加固:游戏出海热潮下,游戏安全面临新挑战

IoT -- 解读物联网四层架构

MySQL learning record 10getting started with JDBC

On the day of resignation, jd.com deleted the database and ran away, and the programmer was sentenced

JS inheritance method

Sort according to a number in a string in a column of CSV file

After PCD is converted to ply, it cannot be opened in meshlab, prompting error details: ignored EOF

Fairguard game reinforcement: under the upsurge of game going to sea, game security is facing new challenges

2022.02.13 - NC001. Reverse linked list

sublime text的编写程序时的Tab和空格缩进问题
随机推荐
【MySQL】日志
LDAP application (4) Jenkins access
[luatos-air551g] 6.2 repair: restart caused by line drawing
sublime text中conda环境中plt.show无法弹出显示图片的问题
Verrouillage [MySQL]
egg. JS project deployment online server
Synchronized solves problems caused by sharing
Sublime text in CONDA environment plt Show cannot pop up the problem of displaying pictures
On the day of resignation, jd.com deleted the database and ran away, and the programmer was sentenced
After PCD is converted to ply, it cannot be opened in meshlab, prompting error details: ignored EOF
C语言双指针——经典题型
Double pointeur en langage C - - modèle classique
Leetcode question brushing (5.28) hash table
优秀的软件测试人员,都具备这些能力
tree树的精准查询
查看局域网中电脑设备
Summary of MySQL index failure scenarios
Fairguard game reinforcement: under the upsurge of game going to sea, game security is facing new challenges
MySQL learning records 12jdbc operation transactions
China high purity silver nitrate Market Research and investment strategy report (2022 Edition)