为什么我的图形邻接表不起作用?

Why is not my Adjacency List for graphs working?

我真的是 java 的新手,我想创建一个邻接列表,因为我想编写一个代码来创建一个 graph.Every 时间 运行 它,它显示 er * 或者在方法 addEdge 中,在构造函数中和方法 main.why 中是否显示错误?我需要改变什么?

这是我的代码:

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);

        }
}

我还有一些其他方法和 类 来完成我的图表的代码,但我只发布了这个,因为它在这里显示了错误rors.Please帮助我找出问题所在! 我得到的错误或:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
    at mygraph.java.MyGraph.<init>(MyGraph.java:37)
    at mygraph.java.MyGraph.main(MyGraph.java:62)

您正在初始化大小为 6 的列表,但是当您调用

MyGraph.list[i] = new LinkedList();

您正在引用索引 6,它是 wrong.Remember 基于 0 的索引。 大小为 6 你只能引用从 0 到 5 的索引,否则你将得到 ArrayIndexOutOfbound Exception