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 li开发者_StackOverflow中文版ne 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
}
The syntax that you show is incorrect, you can not declare both the step variable (Foo f) and the collection (Vector v) in the loop. You will get a NullPointerException if the collection (v in your example) is null. As noted above, you will also get a NullPointerException if the collection contains an element that is null.
精彩评论