【问题标题】:Working of Iterator of Collections framework in javaJava中集合框架的迭代器的工作
【发布时间】:2016-06-01 13:31:34
【问题描述】:

目标是从用户那里获取输入并在代码本身中添加一个字符串“###”,然后再次添加一些字符串。目标是打印添加“###”后获取的输入。 代码是:

import java.util.*;
public class Main
{
    @SuppressWarnings("rawtypes")
    static Iterator func(ArrayList mylist)
    {
        Iterator it=mylist.iterator();
        while(it.hasNext())
        {
            Object element = it.next();
            if(element instanceof String) { 
                break;
            }
        }
        return it;
    }

    @SuppressWarnings("unchecked")
    public static void main(String []argh)
    {
        @SuppressWarnings("rawtypes")
        ArrayList mylist = new ArrayList();
        @SuppressWarnings("resource")
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        int m=sc.nextInt();
        for(int i=0;i<n;i++)
        {
            mylist.add(sc.nextInt());
        }
        mylist.add("###");
        for(int i=0;i<m;i++)
        {
            mylist.add(sc.next());
        }

        @SuppressWarnings("rawtypes")
        Iterator it=func(mylist);
        while(it.hasNext())
        {
            Object element = it.next();
            System.out.println((String)element);
        }
    }
}

输入是:

2 2
42
10
hello
java

输出是:

hello 
java

我的问题是这里如何只打印 hello 和 java,因为 while 循环在第一次遇到字符串“###”(我们在代码中添加)时中断。

谁能解释一下?

【问题讨论】:

    标签: java collections iterator


    【解决方案1】:
     Object element = it.next();
     if(element instanceof String) { 
        break;
     }
    

    在上面的代码sn-p中,会得到第一个Stringelement,同时迭代器会去next,跳过第一个String元素。

    所以“###”会被忽略,因为它是第一个String类型元素。

    【讨论】:

    • 知道了!非常感谢!
    猜你喜欢
    • 2011-10-07
    • 1970-01-01
    • 1970-01-01
    • 2015-08-17
    • 2011-04-25
    • 2017-12-08
    • 2014-11-29
    • 1970-01-01
    • 2010-11-16
    相关资源
    最近更新 更多