[英]error in my for loop over a hashmap
it's my first time to deal with HashMap
's and i'm trying to make a simple loop to loop over each key but the code doesn't even enter the for-loop
...can anyone help me plz? 这是我第一次处理HashMap
并且我试图做一个简单的循环来遍历每个键,但代码甚至没有进入for-loop
...任何人都可以帮助我PLZ?
for(int i=0; i< ackPkts.size()-1; i++){
System.out.println("yasmin");
if (ackPkts.get(i).getAckNo() == ackPkts.get(i-1).getAckNo()){
System.out.println("there's a retransmissionS here");
}else{
v = value.indexOf(ackPkts.get(i).getAckNo() -1);
}
}
it doesn't even print yasmin ! 它甚至不打印yasmin !
You cannot iterate a map like an Array
or a List
, even if your keys are Integer
and consecutive it is highly discouraged. 您不能像Array
或List
那样迭代地图,即使您的键是Integer
,也不是连续的,因此非常不鼓励。
for(int i=0; i< ackPkts.size()-1; i++){ // WRONG!
To iterate each entry of a map use the entrySet()
method: 要迭代映射的每个条目,请使用entrySet()
方法:
for (Map.Entry<Integer, String> entry : map.entrySet())
{
System.out.println(entry.getKey() + "/" + entry.getValue());
}
Also as noted in others answers, there is plenty of mistakes because of -1
you used with size, but this will be avoided iterating the entrySet
of your Map
;) 同样如其他答案所述,有很多错误,因为你使用大小的-1
,但这将避免迭代你的Map
的entrySet
;)
The code snippet that you have mentioned is not clear enough to understand what has to be done inside the loop. 您提到的代码片段不够清楚,无法理解循环内部必须完成的操作。
Hope this would help you. 希望这会对你有所帮助。
Set set = ackPkts.entrySet();
Iterator i = set.iterator();
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
This is the way to loop over the HashMap. 这是循环HashMap的方法。
Your for loop condition is wrong. 你的for循环条件是错误的。
It should be : 它应该是 :
for(int i=0; i< ackPkts.size(); i++) {
And still if it does not print anything, then it means that ackPkts
is empty. 而且如果它没有打印任何东西,那么这意味着ackPkts
是空的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.