当我尝试访问我创建的数组的元素并且不知道原因时,我不断收到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 linebut 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.
更多推荐
发布评论