数组转Iterator"/>
ListString数组转Iterator
引子:看阿里开发手册时,其中提到不要在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.apachemons.collections.IteratorUtils.toList(iStr);//第三种 用Lists的newArrayList方法List strList2 = com.googlemon.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出去。
具体原因为什么不得而知,在此做下备注。如果有高手也碰到过这种情况,且 有自己的见解亦或是解决了的,请告知一下,谢谢
更多推荐
ListString数组转Iterator
发布评论