ListString数组转Iterator

编程入门 行业动态 更新时间:2024-10-15 22:26:55

ListString<a href=https://www.elefans.com/category/jswz/34/1771288.html style=数组转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

本文发布于:2024-03-23 16:53:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1740563.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   ListString   Iterator

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!