Arrays.asList cannot add and remove element

Xuda Lu
1 min readAug 12, 2019

--

You will get UnsupportedOperationException if you initiate array by Arrays.asList.

@Test
public void RemoveSomeElement() {

List<String> stringList = Arrays.asList ("lu", "zhangjie", "zhangsan", "lu", "zhangjie", "liming");
List<String> subList = new ArrayList<String> () {{
add ("lu");
add ("zhangjie");
}};
stringList.removeAll (subList);
stringList.remove ("zhangsan");
System.out.println (stringList.stream ().collect (Collectors.joining (",")));
}

you can use two way to escape Exception

1 List<String> stringList =new ArrayList<string>();stringList.add(“lu”);

2 List<String> stringList =new ArrayList<> ( Arrays.asList (“lu”,”zhangjie”))

--

--

Xuda Lu
Xuda Lu

No responses yet