Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(AbstractList.java:161)
at com.day14.Operation.footballTeam(Operation.java:106)
at com.day14.Operation.main(Operation.java:51)
在调用当对List列表进行add()和remove()操作时出现java.lang.UnsupportedOperationException异常。把数组转成List的操作:
String[] balls = {"科特迪瓦","阿根廷","澳大利亚","塞尔维亚","荷兰","尼日利亚","日本","美国","中国","新西兰","巴西","比利时","韩国","喀麦隆","洪都拉斯","意大利"};
List<String> ballsList = Arrays.asList(balls);
异常分析:java.lang.UnsupportedOperationException是指请求的方法不被支持的异常。在从 Arrays.asList()转换过来的List的不支持add()和remove()方法,这是由于从 Arrays.asList() 返回的是返回 java.util.ArraysArrayList,而不是ArrayList。ArraysArrayList和ArrayList都是继承AbstractList,add() 和 remove() 等方法在AbstractList中默认 throw UnsupportedOperationException而不做任何操作。ArrayList重写这些方法对List进行操作,而Arrays$ArrayList却没有重写add()和remove() 等方法,所以对从 Arrays.asList() 转化过来的List进行 add() 和remove() 会出现 UnsupooortedOperationException异常
解决办法:
使用Iterator迭代器或者转化成ArrayList。
String[] balls = {"科特迪瓦","阿根廷","澳大利亚","塞尔维亚","荷兰","尼日利亚","日本","美国","中国","新西兰","巴西","比利时","韩国","喀麦隆","洪都拉斯","意大利"};
List<String> liB = Arrays.asList(balls);
List<String> ballsList = new ArrayList<String>(liB);
网友评论