Android: Issue during Arraylist declaration

青春壹個敷衍的年華 提交于 2019-12-04 05:47:54

问题


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.



来源:https://stackoverflow.com/questions/8067382/android-issue-during-arraylist-declaration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!