我真的是Java新手,我想创建一个邻接表,因为我想编写代码来创建图形,每次运行它时,它都会在er *或方法addEdge中,构造函数中以及方法main.w为什么会显示错误?我需要改变什么?
这是我的代码:
public class MyGraph {
/**
* @param args the command line arguments
*/
static LinkedList<Integer> list[]; //list which shows which node is linked to which
private final int numberofVertices;
public MyGraph(int vertices) { //constructor
numberofVertices = vertices;
MyGraph.list = new LinkedList[numberofVertices];
for (int i = 1; i <= vertices; i++)
MyGraph.list[i] = new LinkedList(); //here it shows ER*OR line 37
}
void addEdge(int src, int dest)
{
list[src].add(dest); //here it shows ER*OR
}
public static void main(String[] args) {
MyGraph o = new MyGraph(6);
o.addEdge(5, 1); //here it shows ER*OR line 62
o.addEdge(6, 1);
o.addEdge(1, 2);
o.addEdge(2, 3);
o.addEdge(2, 4);
}
}
我还有一些其他方法和类来完成图形的代码,但是我只发布了此代码,因为在这里它向我展示了错误,请帮助我找出错误所在。 !!! 我得到的错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at mygraph.java.MyGraph.<init>(MyGraph.java:37)
at mygraph.java.MyGraph.main(MyGraph.java:62)
答案 0 :(得分:0)
您正在初始化大小为6的列表,但在调用
时MyGraph.list[i] = new LinkedList();
您引用的索引6不正确,请记住基于0的索引。 大小为6时,您只能引用从0到5的索引,否则会出现ArrayIndexOutOfbound异常