简体   繁体   中英

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?

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 !

You cannot iterate a map like an Array or a List , even if your keys are Integer and consecutive it is highly discouraged.

for(int i=0; i< ackPkts.size()-1; i++){   // WRONG!

To iterate each entry of a map use the entrySet() method:

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 ;)

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.

Your for loop condition is wrong.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM