2

Hi im having trouble with the selected code. Can anyone tell help me figure out why the section in bold wont work?

    Graph(int vertices) {
        int vertices;
        LinkedList<Edge> [] adjacencylist;

        this.vertices = vertices;
        adjacencylist = new LinkedList[vertices];
        //initialize adjacency lists for all the vertices
        for (int i = 0; i < vertices ; i++) {
            adjacencylist[i] = new LinkedList<>();
        }
    }

    public void addEgde(String source, String destination, int weight) {
        Edge edge = new Edge(source, destination, weight);
        **adjacencylist[source].addFirst(edge); //for directed graph**
    }
TylerH
  • 20,799
  • 66
  • 75
  • 101
AlFonse
  • 21
  • 2
  • Do you have two variables `adjacencylist`, one in the class and one in the constuctor's scope? – Mark Jeronimus Nov 15 '19 at 15:14
  • Variables vertices and adjacencylist are declared in a static class called 'Graph' that is just before the code listing i posted – AlFonse Nov 15 '19 at 15:17
  • There's no such thing in Java as a `static class`. With my comment I was hoping to make you realize your error yourself if the answer is 'yes' – Mark Jeronimus Nov 15 '19 at 15:20
  • 1
    Any array is indexed by an integer. You are using a String as an index in the addEgde method. – fedup Nov 15 '19 at 15:41
  • What would be the solution if i needed the source to be a string instead of an int? Would parseInt work? – AlFonse Nov 15 '19 at 15:55
  • You would have to explain what "String source" is and how it is used within Edge. Is it always an integer as a string (like "123")? – fedup Nov 15 '19 at 16:49

1 Answers1

0

You are defining a local variable "adjacencyList" in the constructor with the same name as the class variable. The local variable overrides the class variable and the class variable remains null. Also, the source parameter can not be used as an index into an array. It must be an integer.

public class Graph {

    int vertices;
    private LinkedList<Edge> [] adjacencylist;

    Graph(int vertices) {

        this.vertices = vertices;
        adjacencylist = new LinkedList[vertices];
        //initialize adjacency lists for all the vertices
        for (int i = 0; i < vertices ; i++) {
            adjacencylist[i] = new LinkedList<>();
        }
    }

    public void addEgde(int source, String destination, int weight) {
        Edge edge = new Edge(source, destination, weight);
        adjacencylist[source].addFirst(edge); //for directed graph
    }

}
fedup
  • 1,209
  • 11
  • 26