Reputation: 3341
I'm doing an ''generic class'' exercise from my textbook right now, trying to implement a Graph data structure using a HashMap as the underlying structure, with keys being nodes in the Graph, and the values of the keys being a HashSet of the nodes adjacent to that node. The beginning of the code looks like this:
public class Graph <T> {
public HashMap<T, HashSet<T>> foo_graph;
//... Code ...
I must mention, both the keys and values in the HashSet must be the same type, this is the reason for the T placeholder. With all my methods written out, I'm trying to test this with a static void main
block, but Eclipse keeps giving me NullPointerExceptions
whenever I try to print the Graph (which has a working ToString method already given to me):
public static void main(String[] args) {
Graph<Integer> g = new Graph<>();
g.addNode(5, [5,3,7]); //Trying to add 5,3,7 to the HashSet, but Eclipse is saying I can't do this.
System.out.println(g);
}
This is my addNode method by the way, I can't seem to add anything the Graph either.
public void addNode(T node_key, HashSet<T> node_value ) {
main_graph.put(node_key, node_value);
Eclipse is telling me at the addNode line in my static void testing block that:
The method addNode(Integer, HashSet<Integer>) in the type Graph<Integer> is not applicable for the arguments (int, int, int, int)
Does anyone know why this is? I just can't seem to get it working, I'm stumped. Neither creating a
Upvotes: 0
Views: 2059
Reputation: 79877
Sure. The syntax of putting stuff in square brackets like you've done just doesn't exist. I have found that the easiest way to initialise a HashSet
is with the Arrays.asList
static method. I would write something like this.
g.addNode(5, new HashSet<Integer>(Arrays.asList(5, 3, 7)));
Upvotes: 1
Reputation: 6969
I have to agree with Eclipse. You can't do this:
g.addNode(5, [5,3,7]);
Java won't know how [5,3,7]
is magically turning into a HashSet.
What you can do is this:
HashSet<Integer> set = new HashSet<>();
set.add(5);
set.add(3);
set.add(7);
g.addNode(5, set);
Upvotes: 0