有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java列表不为空,但poll方法返回null

我的方法应该计算集合nodes中节点的深度,但对于某些树,会调用NullPointerException,这是因为queue.poll()返回null。在该方法的描述中,据说queue.poll()当且仅当队列为空时返回null。这种情况是在while循环中检查的,所以我的问题是,为什么会发生这种错误以及如何修复它

private Map<Tree, Integer> determineDepth(Tree root, Set<Tree> nodes) {
    Map<Tree, Integer> depthMap = new HashMap<>();
    Map<Tree, Boolean> visited = new HashMap<>();
    LinkedList<Tree> queue = new LinkedList<Tree>();

    depthMap.put(root, 0);
    visited.put(root, true);
    queue.add(root);
    Tree node;
    while (queue.size() != 0) {
        node = queue.poll();
        int depth = depthMap.get(node);
        for (Tree child : node.children()) {
            depthMap.put(child, depth + 1);
            visited.putIfAbsent(child, false);
            if (!visited.get(child)) {
                visited.put(child, true);
                queue.add(child);
            }
        }
    }
    return depthMap;
}

共 (1) 个答案

  1. # 1 楼答案

    如果将null添加到LinkedList,它将被保留。e、 g

    List l = new LinkedList();
    l.add(null);
    assert l.size() > 0;
    Object o = l.poll(); // == null