我知道大多数人都犯了不初始化Arraylist的错误,这就是他们获得NullPointerException的原因。
但在我的课堂上,我已经初步化了我的Arraylist,当我尝试添加它时,我仍然得到异常。
protected int V;
protected int E;
protected boolean[][] adjacencyMatrix;
public int i;
public int[] num;
public ArrayList<String> edges;
public SimpleGraph(int V) {
this.V = V;
this.E = 0;
this.adjacencyMatrix = new boolean[V][V];
edges = new ArrayList<String>();
num = new int[V];
}
public void DFS(int V) {
num[V] = i++;
for(int u = 0; u < getV(); u++)
{
if(adjacencyMatrix[V][u] == true && u != V)
{
if(num[u] == 0)
{
Integer temp = new Integer(num[u]);
edges.add("anything");
DFS(u);
}
}
}
}
您可以假设我已正确添加到adjacencyMatrix。
当我尝试添加到Arraylist时,为什么会出现NullPointerException?
答案 0 :(得分:1)
您宣布了queue ArrayList
protected ArrayList<Integer> queue;
但初始化了edges ArrayList
edges = new ArrayList<String>();
因此,请尝试初始化queue ArrayList
queue = new ArrayList<Integer>();
答案 1 :(得分:0)
在您的类变量中,您有
protected ArrayList<Integer> queue
,
但在SimpleGraph()
构造函数中,您有
edges = new ArrayList<String>();
edges
应为queue
,反之亦然。
此外,edges
如果您认为它与ArrayList<String>
的类型相同,则应为queue
。
答案 2 :(得分:0)
package test_001;
import java.util.ArrayList;
public class Vanste {
protected int V = 5;
protected static int E;
protected static boolean[][] adjacencyMatrix;
public static int i = 0;
public static int[] num;
public static ArrayList<String> edges;
public static void SimpleGraph(int V) {
E = 0;
adjacencyMatrix = new boolean[V][V];
edges = new ArrayList<String>();
num = new int[V];
}
public static void DFS(int V) {
num[V] = i++;
for(int u = 0; u < V-1; u++)
{
/*System.out.println("A1");
if(adjacencyMatrix[V-1][u] == true && u != V-1)
{ System.out.println("A1");
if(num[u] == 0)
{*/
Integer temp = new Integer(num[u]);
edges.add(temp.toString() + ":");
DFS(u);
//}
//}
}
}
public static void main(String[] args) {
SimpleGraph(15);
DFS(5);
for(int i =0; i< edges.size(); i++) {
System.out.println("" + edges.get(i) + "\n");
}
}
}
此示例正常。在将项添加到列表之前,您的逻辑出了问题。 顺便说一下,你正在使用并递增从未初始化的变量i。 这种说法永远不会成立。 (adjacencyMatrix [V] [u] == true) 能否请你给我一个工作函数,而不是我的SimpleGraph(15)和DFS(5)。