我想偷个懒,结果我多会了个知识点——UnsupportedOperationException

it2025-03-05  25

import org.junit.Test; import java.util.Arrays; import java.util.Collection; /** * description: 集合类测试 * author: Leet * create: 2020-10-21 19:51 **/ public class CollectionTest { @Test public void collectionTest(){ Collection<Integer> collection = Arrays.asList(0,1,2,3,4); System.out.println(Arrays.toString(collection.toArray())); Integer[] moreInts = {5,6,7,8,9}; collection.addAll(Arrays.asList(moreInts)); System.out.println(Arrays.toString(collection.toArray())); } }

请您看看上面的代码有何错误? 是不是非常完美呢?

先别着急下定论,看看运行结果吧! 上面的代码是竟然错的!!!!!

我就想偷个懒,没想做啥啊。 正在快乐玩耍的我忽然不快乐了——我必须解决这个问题啊。

原来是这样的啊。

Arrays.asList() 方法是会生成一个 List 对象的 但,该 List 对象非 javautil.List 对象 这两个对象都继承自 AbstractList 类

Arrays 类在内部写了一个继承自 AbstractList 类的内部类

但它没有重写 addAll()方法!!! addAll()方法 AbstractList中是默认throw UnsupportedOperationException而且不作任何操作。java.util.ArrayList重新了g该方法而 Arrays的内部类ArrayList没有重新,所以会抛出异常

既然,明白了为什么就好改了!

import org.junit.Test; import java.util.Arrays; import java.util.ArrayList; import java.util.Collection; /** * description: 集合类测试 * author: Leet * create: 2020-10-21 19:51 **/ public class CollectionTest { @Test public void collectionTest(){ Collection<Integer> collection = new ArrayList<>(Arrays.asList(0,1,2,3,4)); System.out.println(Arrays.toString(collection.toArray())); Integer[] moreInts = {5,6,7,8,9}; collection.addAll(Arrays.asList(moreInts)); System.out.println(Arrays.toString(collection.toArray())); } }

最新回复(0)