Why does this code sometimes throw a NullPointerException?

前端 未结 3 907
独厮守ぢ
独厮守ぢ 2021-01-13 21:13

Consider the following Java source:

if( agents != null ) {
  for( Iterator iter = agents.keySet().iterator(); iter.hasNext(); ) {
    // Code that uses iter.         


        
3条回答
  •  Happy的楠姐
    2021-01-13 22:15

    Shouldn't that be a while loop?

    if (agents != null) {
        Iterator iter = agents.keyset().iterator();
        while (iter.hasNext()) {
            //some stuffs here
        }
    }
    

    or a for each?

    if (agents != null) {
        //Assuming the key is a String
        for (String key : agents.keyset()) {
            //some stuffs here
        }
    }
    

提交回复
热议问题