引子:看阿里開發手冊時,其中提到不要在forEach裏面進行元素的remove/add。否則會有錯誤發生,親自試了一下,果然會有問題。如下
List<String> strList = new ArrayList<>();
strList.add("1");
strList.add("2");
for (String str : strList) {
if (Objects.equals("2", str)) {
strList.remove(str);
}
}
System.out.println(strList.toString());
其建議是這樣
List<String> strList = new ArrayList<>();
strList.add("1");
strList.add("2");
Iterator iStr = strList.iterator();
while (iStr.hasNext()) {
String temp = iStr.next().toString();
if (Objects.equals("2", temp)) {
iStr.remove();
}
}
這樣是正常的,但無法轉成list展示看效果,我百度搜了一下資料,有幾種方法,我這邊一一進行測試,測試結果如下:
List<String> strList = new ArrayList<>();
strList.add("1");
strList.add("2");
Iterator iStr = strList.iterator();
List<String> newList = new ArrayList<>();
while (iStr.hasNext()) {
String temp = iStr.next().toString();
if (Objects.equals("2", temp)) {
iStr.remove();
} else {
//第一種 直接遍歷組合新數組
newList.add(temp);
}
}
//第二種 用IteratorUtils的toList方法
List strList1 = org.apache.commons.collections.IteratorUtils.toList(iStr);
//第三種 用Lists的newArrayList方法
List strList2 = com.google.common.collect.Lists.newArrayList(iStr);
System.out.println("第一種遍歷中直接組合:" + newList.toString());
System.out.println("第二種IteratorUtils轉:" + strList1.toString());
System.out.println("第三種Lists.newArrayList轉:" + strList2.toString());
結果運行
結果用那兩個提供的工具類轉成list都顯示爲空,然後debug了一下
在IteratorUtils.toList() 內部的iterator.hasNext()的時候爲空,所以直接返回了一下空的list出去。
具體原因爲什麼不得而知,在此做下備註。如果有高手也碰到過這種情況,且 有自己的見解亦或是解決了的,請告知一下,謝謝