引子:看阿里开发手册时,其中提到不要在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>数组转Iterator-再转回List的问题测试

其建议是这样

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<String>数组转Iterator-再转回List的问题测试

结果用那两个提供的工具类转成list都显示为空,然后debug了一下

List<String>数组转Iterator-再转回List的问题测试

在IteratorUtils.toList()  内部的iterator.hasNext()的时候为空,所以直接返回了一下空的list出去。

具体原因为什么不得而知,在此做下备注。如果有高手也碰到过这种情况,且 有自己的见解亦或是解决了的,请告知一下,谢谢

相关文章:

  • 2022-12-23
  • 2021-12-18
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-11-19
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案