Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/flash/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么我的图表邻接列表不起作用?_Java_Linked List_Indexoutofboundsexception - Fatal编程技术网

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

Java 为什么我的图表邻接列表不起作用?,java,linked-list,indexoutofboundsexception,Java,Linked List,Indexoutofboundsexception,我对java非常陌生,我想创建一个邻接列表,因为我想编写一个代码来创建一个图形。每次我运行它时,它都会在方法addEdge、构造函数和方法main中显示er*或。为什么它会显示错误??我需要改变什么 这是我的代码: public class MyGraph { /** * @param args the command line arguments */ static LinkedList<Integer> list[]; //list w

我对java非常陌生,我想创建一个邻接列表,因为我想编写一个代码来创建一个图形。每次我运行它时,它都会在方法addEdge、构造函数和方法main中显示er*或。为什么它会显示错误??我需要改变什么

这是我的代码:

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

        }
}
公共类MyGraph{
/**
*@param指定命令行参数
*/
静态LinkedList列表[];//显示链接到哪个节点的列表
私有最终整数;
公共MyGraph(int顶点){//构造函数
顶点数=顶点数;
MyGraph.list=新链接列表[numberofVertices];

对于(int i=1;i您正在初始化大小为6的列表,但在您呼叫时

MyGraph.list[i] = new LinkedList();
您引用的索引6是错误的。请记住基于0的索引。 如果大小为6,则只能引用从0到5的索引,否则将得到ArrayIndexOutofBond异常

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