views:

42

answers:

3

Why does this line cause a NullPointerException:

    List<Foo> foos = new ArrayList<Foo>(userDetailsService.getFoos(currentUser));

The getFoos method simply returns a Collection of Foos:

    public Collection<Foo> getFoos(final String username)

I can't tell if the NullPointerException refers to getFoos returning null or some problem with the cast from a Collection to an ArrayList.

+2  A: 

Depends on the stacktrace. Head to the first line. If it points to java.util.ArrayList.<init>, then getFoos() has returned null. Or if it points to the particular line in your question, then userDetailsService is null.

BalusC
+1  A: 

I can't tell if the NullPointerException refers to getFoos returning null or some problem with the cast from a Collection to an ArrayList.

And that's why we have the Law of Demeter. If you separate the two statements that have been conjoined together, you would have better luck in resolving the issue.

However, it should be apparent that a null collection (not an empty collection) is returned which is responsible for the issue. After all, invoking the ArrayList constructor with a null collection will not result in a null pointer exception.

EDIT:

My bad. The ArrayList constructor will attempt to copy the collection. So a null collection can cause a null pointer exception. I stick to my original recommendation of decoupling the two statements. Coding in the following manner will help identify the issue faster:

Collection<Foo> myFoos = userDetailsService.getFoos(currentUser);
List<Foo> foos = new ArrayList<Foo>(myFoos);
Vineet Reynolds
Fully agree with splitting the statement into 2 separate statements. Should then make it obvious which is failing.
P72endragon
A: 

A failed typecast cannot give you a NullPointerException.

Object o = new Integer(43);
String s = (String) o;  // throws ClassCastException

Typecasting a null will not throw an exception at all.

o = null;
String s = (String) o;  // no exception

Therefore the theory that getFoo is returning a null is plausible. But it could also be that userDetailsService is null or that the NPE is thrown in getFoo.

You should be able to distinguish these cases by carefully reading the stacktrace ... which you didn't include in your question (tsk, tsk).

Stephen C