-1

I am solving DFS problem so i used array of a ArrayList. Here is my code

ArrayList<Node> graph[] = new ArrayList[N+1];

         int u, v, w;
         for (int i = 1; i <=N; i++){
             graph[i] = new ArrayList<Node>();
       }

         for(int i=0;i<N-1;i++){

              u=sc.nextInt();
               v=sc.nextInt();
               w=sc.nextInt();


             graph[u].add(new Node(v,w));
             graph[v].add(new Node(u,w));

        }
System.out.println(graph[1].get(0));----------(1) 

For above print statement i got output Node@1db9742.I don't know why i am getting this out. My input:

1
3
1 2
1 3
2 3

Plz help me on how to print exact output from array of arrayList

Edit: Node class:

class Node {
    static int i;
    int distance;

    Node(int i, int distance) {
        this.i = i;
        this.distance = distance;
    }
}
Gurwinder Singh
  • 38,557
  • 6
  • 51
  • 76
coder_247
  • 13
  • 4

2 Answers2

0

You'll have to override the Node class' toString() method as per your needs.

For e.g - If you want only distance in text representation of your class, you can do something like -

class Node {
    static int i;
    int distance;

    Node(int i, int distance) {
        this.i = i;
        this.distance = distance;
    }

    @Override
    public String toString() {
        return Integer.toString(distance); // Change as per your needs
    }

}

More on this:

Community
  • 1
  • 1
Gurwinder Singh
  • 38,557
  • 6
  • 51
  • 76
0

You must override toString method for Node class, so System.out.println() method can use it to display what you are expecting. like this

class Node {
    static int i;
    int distance;

    Node(int i, int distance) {
        this.i = i;
        this.distance = distance;
    }

    @Override
    public String toString() {
        return "Node{" +
                "i=" + i + "," +
                "distance=" + distance +
                '}';
    }
}
Saeed Zhiany
  • 2,051
  • 9
  • 30
  • 41
  • ohh i got it i can't tick both the ans srry @GurwinderSingh – coder_247 Jan 01 '17 at 15:50
  • You should accept only the one answer that solve your problem better, if you think the other answer is better, it's OK. Instead, you can upvote all the correct answers (after you get 20 reputations). Happy coding :) – Saeed Zhiany Jan 01 '17 at 16:59