gpt4 book ai didi

java - 为集合循环

转载 作者:行者123 更新时间:2023-12-01 06:58:08 24 4
gpt4 key购买 nike

我有以下代码:

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**************

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

最佳答案

那是因为当你这样做时:

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
}

关于java - 为集合循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6065045/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com