循环为集

时间:2011-05-19 21:23:03

标签: java

我有以下代码:

LinkedHashMap<String,ArrayList<String>> h;
Set set = h.entrySet();     
Iterator i = set.iterator();
        while(i.hasNext()) {
            System.out.println(i.next());
            Map.Entry me = (Map.Entry)i.next();
            String currentSegString = (String) me.getKey();

            System.out.println(currentKey+"**************");
        }

打印出来:

1=[]
2**************
3=[A, B, C]
4**************
5=[]

然后我删除了一行System.out.println(i.next());

LinkedHashMap<String,ArrayList<String>> h;
Set set = h.entrySet();     
Iterator i = set.iterator();
        while(i.hasNext()) {

            Map.Entry me = (Map.Entry)i.next();
            String currentSegString = (String) me.getKey();

            System.out.println(currentKey+"**************");
        }

它打印出来:

1**************
2**************
3**************
4**************
5**************

为什么不在第一种情况下为每个键打印**************

3 个答案:

答案 0 :(得分:6)

那是因为当你这样做时:

System.out.println(i.next());

您正在跳到下一行,然后Map也会.next()

因此,您只能看到可能的5行中的2行。

说明:

     while(i.hasNext()) { 
        System.out.println(i.next()); //skip one  #1, #3, #5
        Map.Entry me = (Map.Entry)i.next(); //goto next one #2, #4
        String currentSegString = (String) me.getKey();

        System.out.println(currentKey+"**************"); //output #2,4
    }

第二段代码:

    while(i.hasNext()) {

        Map.Entry me = (Map.Entry)i.next(); //goto next one #1, #2, #3, #4, #5
        String currentSegString = (String) me.getKey();

        System.out.println(currentKey+"**************"); //output #1,2,3,4,5
    }

解决这个问题的方法是:

    while(i.hasNext()) {
        Object temp = i.next(); //goto next one #1, #2, #3, #4, #5
        System.out.println(temp);
        Map.Entry me = (Map.Entry)temp; 
        String currentSegString = (String) me.getKey();

        System.out.println(currentKey+"**************"); //output #1,2,3,4,5
    }

答案 1 :(得分:2)

在第一段代码中,你有两次调用i.next(),这意味着你的循环只会执行少于第二段代码的次数。

答案 2 :(得分:1)

这是您的代码应该是什么样的,以获得您想要的输出:

Map.Entry me;
LinkedHashMap<String,ArrayList<String>> h;
Set set = h.entrySet();     
Iterator<Map.Entry> i = set.iterator();
while(i.hasNext()) 
{
    me = i.next();
    System.out.println(me);
    String currentSegString = (String) me.getKey();
    System.out.println(currentKey+"**************");
}

这样您只需拨打i.next();一次。