Android:Arraylist 声明期间的问题 [英] Android: Issue during Arraylist declaration

查看:23
本文介绍了Android:Arraylist 声明期间的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我像这样声明 Arraylist-

If I declare Arraylist like this-

private ArrayList<Integer[]> nodeList;

然后,在向其中添加数组时,得到 NullPointerException

then, while adding array into it, getting NullPointerException

但是,如果我把它改成-

But, if I change it to-

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

-它工作正常.

为什么第一个失败了!

推荐答案

第一个只声明了一个变量,而没有创建实际的对象.只有当你使用 new 时,你才真正创建了对象.

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

在与 C++ 不同的 Java 中,声明一个变量不会为其分配局部变量.要实际创建对象,您需要显式创建它[在您的示例中:通过使用 new 关键字].
(*)请注意,这仅适用于 reference 类型对象,以及 java 原语是用声明创建的.

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.

这篇关于Android:Arraylist 声明期间的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆