List/Set通过迭代器Iterator删除元素

  1. 数组迭代器删除元素
错误示例,会报UnsupportedOperationException异常:
String str = "a,b,c,d,e";
String[] splits = str.split(",");
List<String> list = Arrays.asList(splits);
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()){
	String nextStr = iterator.next();
	iterator.remove();
}
正确示例:
String str = "a,b,c,d,e";
String[] splits = str.split(",");
List<String> list =new ArrayList<>();
//for循环
for(int i = 0; i < splits.length; i++){
	list.add(splits[i]);
}
//或者foreach
Arrays.stream(splits).forEach( o -> list.add(o));

Iterator<String> iterator = list.iterator();
while(iterator.hasNext()){
	String nextStr = iterator.next();
	iterator.remove();
}

2.不管是什么集合,都需要先iterator.next()获取元素,然后再调用iterator.remove()删除元素。

你可能感兴趣的:(list,数据结构,java,spring)