开发者

Loop for the Set

I have the following code:

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+"**************");
        }

Prints out this:

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

But then I remove one line 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+"**************");
        }

And it prints out this:

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

Why doesn't it print ************** in the first case for each key?


That is because when you do :

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

You are skipping to the next line, and then the Map also does .next()

Therefor you are only seeing 2 out of the possible 5 lines.

Explanation:

     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
    }

Second code:

    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
    }

A way to fix this would be:

    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
    }


In the first piece of code, you have two calls to i.next(), which means that your loop will only execute fewer times than in the second piece of code.


This is what your code should look like to get your desired output:

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+"**************");
}

This way you only call i.next(); once.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜