TheWatisit
TheWatisit

Reputation: 7

Java for loops null pointer

I have the class Memory which is a list of blocks, and Blocks which is a list of tuples and Tuple.

Memory m;
for(Block b:m.blocklist){
    for (Tuple t:b.tuplelist){
        //do something
    }
}

The above code works fine, every single tuple goes through it but the problem is even after the last tuple, it continues on leading to a null pointer exception. I can't modify the memory class, blocks nor tuples so how do I avoid the error?

Upvotes: 0

Views: 101

Answers (3)

NewOutlaw
NewOutlaw

Reputation: 64

Perhaps in the last Blocklist the Tuplelist is null?

Upvotes: 0

Olimpiu POP
Olimpiu POP

Reputation: 5067

Supposing that the NPE appears on the line of the second for you can add a check for null:

Memory m;
for(Block b:m.blocklist){
   if (b != null) {
     for (Tuple t:b.tuplelist){
        //do something
      }
   }
 }

Upvotes: 1

Bohemian
Bohemian

Reputation: 425168

If one of the blocks is null, you'll get an NPE.

Check for null:

Memory m;
for(Block b:m.blocklist){
    if (b != null) {
        for (Tuple t:b.tuplelist){
            //do something
        }
    }
}

Upvotes: 0

Related Questions