Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null pointer exception in enhanced for loop over Vector

How could this code throw a null pointer exception?

for (Foo f : Vector<Foo> v)
{
    f.doStuff(); // this line throws a NullPointerException
}

Even if the Vector is empty, shouldn't the inside block just never be executed?

like image 992
wohanley Avatar asked Mar 18 '26 21:03

wohanley


1 Answers

The Vector is not empty. As you say, if it was then the loop body would not be executed.

If you get an NPE on that line, it means that one (or more) of the elements of the Vector is null.


I should also point out that the example code is syntactically incorrect. It should probably read something like this:

Vector<Foo> v = ...    
for (Foo f : v)
{
    f.doStuff(); // this line throws a NullPointerException
}
like image 129
Stephen C Avatar answered Mar 20 '26 11:03

Stephen C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!