问题是:
a Two-dimensional array relation[n][2] represent the relation between the nodes, for exemple relation[0] equals {2,4}, so there is an adjancency relation between node 2 and node 4, and contains no cyclic relation.
我想将树结构保存在 HashMap 中,所以我尝试编写如下代码:
Map<Integer, LinkedList<Integer>> graph = new HashMap<Integer, LinkedList<Integer>>();
for (int i = 0; i < n; i++) {
int A = relation[i][0];
int B = relation[i][1];
if (graph.get(A) == null) {
List<Integer> tempList = new LinkedList();
tempList.add(B);
graph.put(A, tempList);
} else {
graph.get(A).add(B);
}
if (graph.get(B) == null) {
List<Integer> tempList = new LinkedList();
tempList.add(A);
graph.put(B, tempList);
} else {
graph.get(B).add(A);
}
}
似乎不起作用,但我不知道如何修复它,有人可以帮助我吗?谢谢!
最佳答案
代码工作正常(我测试过),只是有一个小的打字错误。
Map<Integer, LinkedList<Integer>>
按原样声明,映射中的值应该是一些 LinkedList
。
但是在这里,您放置了一些List
:
List<Integer> tempList = //[...];
[...]
//Compiler will complain that tempList is a List but a LinkedList is expected.
graph.put(A, tempList);
所以要么创建一些像这样的 LinkedList :
LinkedList<Integer> tempList = new LinkedList<>();
或者声明您的Map
将一些List
作为值:
Map<Integer, List<Integer>>
注意:从 Java 8 开始,您可以像这样使用 Map.computeIfAbsent
:
Map<Integer, LinkedList<Integer>> graph = new HashMap<>();
for (int i = 0; i < n; i++) {
int A = relation[i][0];
int B = relation[i][1];
graph.computeIfAbsent(A, k-> new LinkedList<>()).add(B);
graph.computeIfAbsent(B, k-> new LinkedList<>()).add(A);
}
关于java - 如何在 HashMap 中保存树结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43346321/