java - 如何在 HashMap 中保存树结构?

标签 java hashmap tree-structure

问题是:

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/

相关文章:

java - 以对象列表为键的 HashMap

tabulator - 如何在制表符中过滤树结构中的子项?

recursion - Django CMS 多级下拉菜单

java - 使用 -cp 执行类但未找到类

c++ - HashMap 错误: no match for call to ‘(const __gnu_cxx::

java - 比较 Java 中的两组对象

java - HashTable的get方法打印所有元素

mongodb - 在 MongoDB 中对集合进行递归搜索

Java REST jersey 生成 URL

java - 使用 RxJava 运行代码时出现编译错误