0

I'm trying to implement Graph using adjacency list, but when I try to add new pair into the list it gaves me an NullPointerException. Is there anyone know why it would happen and how to fix it?

Thanks in advance.

My Graph.java is like:

import javafx.util.Pair;
import java.util.*;

public class Graph{
    private final HashMap<String, List<Pair<String, Integer>>> adj;

    public Graph(String filePath) {
        adj = new HashMap<>();
        addEdge("a", "b", 30);
    }

    public void addEdge(String start, String end, int weight) {
        adj.get(start).add(new Pair<>(end, weight));
    }
}

My Main.java is like:

public class Main {
    public static void main(String[] args) {
        Graph gr;

        try {
            gr = new Graph("test.txt");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
Fingalzzz
  • 109
  • 14
  • Fingal - you have not included the stacktrace in your question. Since finding the cause of an NPE without a stacktrace is largely guesswork, your Question was marked as a duplicate of a generic Q&A with answers that explain how to debug and fix NPEs for yourself. Your subsequent revision of the question did not help. – Stephen C Apr 02 '17 at 01:20
  • 2
    However here's a hint. What will `adj.get(start)` return when `adj` is a newly created (and hence empty) `HashMap`? – Stephen C Apr 02 '17 at 01:22

1 Answers1

-1

Just putting new Graph() in your second constructor doesn't initialize it. You just declare a default graph and don't store it anywhere. Now if you use the special function this, you'll get what you want.

public Graph(String filePath) {
    this();
    ...
Arya McCarthy
  • 8,554
  • 4
  • 34
  • 56