-1

I am really new to java and I want to create an Adjacency List because I want to write a code to create a graph.Every time I run it, it shows er*or in the method addEdge, in the constructor and in the method main.why does it show the error?? what I need to change?

This is my code :

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

        }
}

I have also some other methods and classes in order to complete the code for my graph, but i only posted this, because here it shows me the errors.Please help me in order to figure out what is wrong!!! The erors I am getting:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
    at mygraph.java.MyGraph.<init>(MyGraph.java:37)
    at mygraph.java.MyGraph.main(MyGraph.java:62)
Ratish Bansal
  • 1,982
  • 1
  • 10
  • 19
AlwaysLearning
  • 120
  • 1
  • 14

1 Answers1

0

You are initializing the list with size 6, but when you are calling

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

you are referencing index 6 which is wrong.Remember the 0 based indexing. With size as 6 you can only refer index from 0 to 5 otherwise you will get ArrayIndexOutOfbound Exception

Ratish Bansal
  • 1,982
  • 1
  • 10
  • 19