运行如下代码:
List<Integer> list = Arrays.asList(1,2,3);
list.add(4);
报如下异常:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:131)
at java.util.AbstractList.add(AbstractList.java:91)
at com.netease.cms.logic.SitemapBase.main(SitemapBase.java:296)
看了一下,Arrays.asList() 返回java.util.Arrays$ArrayList, 而不是ArrayList
Arrays$ArrayList和ArrayList都是继承AbstractList, add,remove等方法在AbstractList中是默认throw UnsupportedOperationException, ArrayList override这些方法来对list进行操作,但是Arrays$ArrayList没有override这些方法,所以throw UnsupportedOperationException。