循环为集

Pro*_*tak 0 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+"**************");
        }
Run Code Online (Sandbox Code Playgroud)

打印出来:

1=[]
2**************
3=[A, B, C]
4**************
5=[]
Run Code Online (Sandbox Code Playgroud)

但后来我删除了一行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+"**************");
        }
Run Code Online (Sandbox Code Playgroud)

它打印出来:

1**************
2**************
3**************
4**************
5**************
Run Code Online (Sandbox Code Playgroud)

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

Nea*_*eal 6

那是因为当你这样做时:

System.out.println(i.next());
Run Code Online (Sandbox Code Playgroud)

你正在跳到下一行,然后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
    }
Run Code Online (Sandbox Code Playgroud)

第二个代码:

    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
    }
Run Code Online (Sandbox Code Playgroud)

解决这个问题的方法是:

    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
    }
Run Code Online (Sandbox Code Playgroud)