我正在尝试使用函数getNeighbors(int n)
获取图形的所有邻居,但是当从main()
调用函数时,它将不起作用。但是,如果我在main()
之外调用该函数,它将起作用。我有点卡住了...。这是我的代码:
import java.io.*;
import java.util.*;
public class Graph
{
private Map<Integer, HashSet<Integer>> graph;
public Graph() {
this.graph = new HashMap<>();
}
public Graph(int n, double p) {
Graph g = new Graph();
for (int i = 0; i < n; i++){
g.addNode(i);
}
for(int i = 0; i < n; i++){
for(int j = i +1; j < n; j++){
if(Math.random()<p){
g.addEdge(i, j);
}
}
}
}
public void addNode(int node)
{
this.graph.putIfAbsent(node, new HashSet<Integer>());
}
public void addEdge(int v1,int v2) {
this.graph.get(v1).add(v2);
this.graph.get(v2).add(v1);
}
public HashSet<Integer> getNeighbors(int v) {
return this.graph.get(v);
}
public static void main(String[] args) {
Graph graph = new Graph(10,0.8);
System.out.println(graph.getNeighbors(4));
}
}```
您有两个构造函数。第一个初始化this.graph
。第二个没有。您的main
方法调用了第二个构造函数。