Arrays.asList 数组转集合 java.lang.UnsupportedOperationException错误

public static void main(String[] args) {
String[] keyArrayStr = new String[]{"123","ewe","323","093"};
Map<String,String> removeMap = new HashMap<String,String>();
removeMap.put("123", "1");
removeMap.put("ewe", "1");
removeMap.put("323", "1");
removeMap.put("093", "1");

// 注意这里:单纯的使用 Arrays.asList 把数组转换为集合后,使用 .add() .remove() 会报 java.lang.UnsupportedOperationException 错误
原因:Arrays.asList 转换的ArrayList 是内部类,并不是 java.util.ArrayList,内部类下没有 add、remove 方法导致的。
解决方案: new ArrayList(Arrays.asList());
List<String> tempList = new ArrayList(Arrays.asList(keyArrayStr));
for (int i = 0; i < tempList.size(); i++) {
if (removeMap.containsKey(tempList.get(i))) {
tempList.remove(i);
i--;
}
}
keyArrayStr = tempList.toArray(new String[tempList.size()]);

}

猜你喜欢

转载自www.cnblogs.com/wgy1/p/9052380.html