Java 数组 NullPointerException [英] Java array NullPointerException
问题描述
代码块如下:
public static Vertex[] computeSubGraph(Vertex[] AdjList, int[] retiming)
{
Vertex[] subGraph = new Vertex[AdjList.length];
for (int i = 0; i < AdjList.length; i++) {
System.out.println(i);
subGraph[i].nodeDelay = AdjList[i].nodeDelay;
subGraph[i].predecessor = AdjList[i].predecessor;
subGraph[i].mark = AdjList[i].mark;
subGraph[i].starTime = AdjList[i].starTime;
subGraph[i].finishTime = AdjList[i].finishTime;
for (int j = 0; j < AdjList[i].inArcList.size(); j++) {
ArcNode old = AdjList[i].inArcList.get(j);
ArcNode newNode = new ArcNode(old.adjVex, old.arcWeight);
subGraph[i].outArcList.add(newNode);
subGraph[old.adjVex].inArcList.add(newNode);
}
}
return subGraph;
}
这是顶点类:
public class Vertex implements Comparable<Vertex> {
public int arcWeight;
public int preDelay;
public boolean infinite = true;
public int nodeDelay = 0;
public Vertex predecessor = null;
public ArcNode firstArc = null;
public int mark = 0;
public int starTime;
public int finishTime;
public ArrayList<ArcNode> inArcList = new ArrayList<ArcNode>();
public ArrayList<ArcNode> outArcList = new ArrayList<ArcNode>();
}
实际上,我只想将AdjList 中的元素复制到一个新数组子图.但是错误信息显示java.lang.NullPointerException"并显示问题出在subGraph[i].nodeDelay = AdjList[i].nodeDelay;"线.
Actually, I just want to copy the element in AdjList to a new array subgraph. But the error message shows that "java.lang.NullPointerException" and shows the problem lies in "subGraph[i].nodeDelay = AdjList[i].nodeDelay;" line.
我通过打印到控制台进行了测试.并发现 AdjList.length 为 8,问题出现在第一轮;即使我只写subGraph[i].nodeDelay;"没有为其分配任何值,它也会显示错误消息.对此有什么想法吗?提前致谢.
I tested by printing to the console. And found the AdjList.length is 8 and the problem occurs in the very first round; And even when I only write "subGraph[i].nodeDelay;" without assigning any value to it, it also shows the wrong message. Any idea on this? Thanks in advance.
推荐答案
将其添加到循环中:
subGraph[i] = new Vertex();
在访问它之前,您首先需要实例化一个对象(在您的情况下为 subGraph[i]
).
You first need to instantiate an object (subGraph[i]
in your case) before accessing it.
这篇关于Java 数组 NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!