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?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With