从方法返回迭代器

我似乎无法在Iterator从方法返回时打印元素removeTwos()。我试图从列表中删除只有两个字符的元素。


public class Main {


    public static void main(String[] args) {


        // write your code here

        List<String> list = new ArrayList<>();

        list.add("hi");

        list.add("what");

        list.add("who");

        list.add("ok");


        System.out.println(removeTwos(list));

    }


    public static String removeTwos(List<String> stringList) {


        Iterator<String> itr = stringList.iterator();

        for(int i = 0; i < stringList.size(); i++) {

            if(itr.hasNext() && itr.next().length() == 2) {

                itr.remove();

                System.out.println(itr.toString());

            }

        }

        return itr.toString();

    }

}


江户川乱折腾
浏览 169回答 3
3回答

紫衣仙女

问题是:你根本不需要Iterator你想要做的事情。您可以使用列表的方法一一搜索列表中的每个项目。试试这个代码,看看它是否适合你:public class JavaApplication255 {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; // write your code here&nbsp; &nbsp; &nbsp; &nbsp; List<String> list = new ArrayList<>();&nbsp; &nbsp; &nbsp; &nbsp; list.add("hi");&nbsp; &nbsp; &nbsp; &nbsp; list.add("what");&nbsp; &nbsp; &nbsp; &nbsp; list.add("who");&nbsp; &nbsp; &nbsp; &nbsp; list.add("ok");&nbsp; &nbsp; &nbsp; &nbsp; removeTwos(list);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(list);&nbsp; &nbsp; }&nbsp; &nbsp; public static void removeTwos(List<String> stringList){&nbsp; &nbsp; &nbsp; &nbsp; for(int i = stringList.size() - 1; i >= 0 ; i--){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String string = stringList.get(i);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (string.length() == 2){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; stringList.remove(string);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp;}

慕标5832272

要Iterator针对此问题使用 ,您可以将removeTwos方法编辑为如下所示:public static String removeTwos(List<String> stringList) {&nbsp; &nbsp; Iterator<String> itr = stringList.iterator();&nbsp; &nbsp; while (itr.hasNext()) {&nbsp; &nbsp; &nbsp; &nbsp; String value = itr.next();&nbsp; &nbsp; &nbsp; &nbsp; if (value.length() == 2) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(value);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; itr.remove();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return stringList.toString();}使用 时Iterator,在循环遍历列表时从列表中删除元素是安全的。这是一个证明它是安全的链接。

神不在的星期二

除非您需要使用 iter,否则使用流和过滤器很容易 1 班轮。List<String>&nbsp;noTwos&nbsp;=&nbsp;list.stream().filter(s->&nbsp;s.length()&nbsp;!=&nbsp;2).collect(Collectors.toList());
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java