Android: Issue during Arraylist declaration

2020-05-01 08:59发布

问题:

If I declare Arraylist like this-

private ArrayList<Integer[]> nodeList;

then, while adding array into it, getting NullPointerException

But, if I change it to-

private ArrayList<Integer[]> nodeList= new ArrayList<Integer[]>();

-it works fine.

Why the first one fails!

回答1:

The first only declares a variable, but does not create the actual object. only when you use new, you actually create the object.

In java unlike C++, declaring a variable does not allocate a local variable of it. To actually create the object, you need to explicitly create it [in your example: by using the new keyword].
(*)Note that this is only true to reference types objects, and java primitives are created with declaration.