Reputation: 3725
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?
Upvotes: 0
Views: 163
Reputation: 146310
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
}
Upvotes: 6
Reputation:
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.
Upvotes: 1
Reputation: 1431
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.
Upvotes: 2