为什么我不能访问类数组索引(why can i not access a class array index)

编程入门 行业动态 更新时间:2024-10-10 13:15:48
为什么我不能访问类数组索引(why can i not access a class array index)

当我尝试访问我创建的数组的元素并且不知道原因时,我不断收到NullPointerException。 抛出的代码:

TreeNode[] list1; list1 = new TreeNode[1000]; list1[0].edges = new EdgeNode(1); //Throw line

但如果我这样做,它的工作原理:

TreeNode[] list1; list1 = new TreeNode[1000]; list1[0] = new TreeNode(); list1[0].edges = new EdgeNode(1);

而且我不知道为什么。 显然,我可以循环遍历整个数组并制作新的元素,但这不会打败新的点吗? 另外,如果相关,我已经为TreeNode定义了默认构造函数。

I keep getting a NullPointerException when I try to access elements of an array I created and don't know why. The code that throws:

TreeNode[] list1; list1 = new TreeNode[1000]; list1[0].edges = new EdgeNode(1); //Throw line

but if I do this, it works:

TreeNode[] list1; list1 = new TreeNode[1000]; list1[0] = new TreeNode(); list1[0].edges = new EdgeNode(1);

and I don't know why. Obviously I could for loop through the whole array and make new elements but doesn't that defeat the point of new? Also, if relevant, I have defined the default constructor for TreeNode.

最满意答案

您实际上回答了自己的问题:应该单独初始化数组的元素。 默认情况下,它们对于对象数组为null 。 因此NullPointerException 。

You actually answered your own question: elements of an array should be individually initialized. By default they are null for array of objects. Hence NullPointerException.

更多推荐

本文发布于:2023-04-29 07:42:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1335618.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   索引   access   index   array

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!