java - 如何解决数组列表中未知来源的问题?

标签 java for-loop arraylist

我需要获取树节点的所有后代。为此,我编写了一个需要帮助函数的函数。当我想获得结果时,我收到以下错误:

位于 java.base/java.util.ArrayList$Itr.checkForCommodification(来源未知) 在 java.base/java.util.ArrayList$Itr.next(来源未知)

我已经遇到了这个错误,这就是为什么我为每个方法创建了不同的列表:子项、后代、祖先、元素和位置。现在我到处都有错误。

public List<Position<E>> descendants(Position<E> p) throws InvalidPositionException {
    if(p == null || isEmpty())
            throw new InvalidPositionException();
    // remove all positions from list
    descendantList.removeAll(descendantList);
    return descendantsList(p);
}
public List<Position<E>> descendantsList(Position<E> p) {
    if(isInternal(p)) {
        // add child to list and check if the child has also children
        for(Position<E> child : children(p)) {
            descendantList.add(child);
            // if child has also children
            if(isInternal(child))
                descendantsList(child);
        }
    }
    return descendantList;
}

子函数如下所示:

public List<Position<E>> children(Position<E> p) throws InvalidPositionException {
    if(p == null || isEmpty())
        throw new InvalidPositionException();
    else {
        BinaryTreeNode<E> node = (BinaryTreeNode<E>) p;
        childrenList.removeAll(childrenList);
        // add left child first
        if(node.leftChild != null)
            childrenList.add(node.leftChild);
        if(node.rightChild != null)
            childrenList.add(node.rightChild);
        return childrenList;
    }
}

为此我创建了不同的列表:

- ArrayList for children: childrenList
- ArrayList for descendants: descendantsList

如何解决这个错误?

编辑:我用clear替换了所有removeAll。它适用于此方法的后代,但作为一个例子,我的高度方法仍然有相同的错误:

public int height() throws EmptyTreeException {
    if(isEmpty())
        throw new EmptyTreeException();
    else
        return heightOf(root);
}
private int heightOf(Position<E> p) {
    if(isExternal(p))
        return 0;
    else {
        int h = 0;
        for(Position<E> child : children(p)) {
            h = Math.max(h,heightOf(child));
        }
        return h + 1;
    }
}

最佳答案

我是这样解决这个问题的: 我为每个使用子列表的方法创建了一个新列表。这样我就没有收到以下错误:

在 java.base/java.util.ArrayList$Itr.checkForCommodification(未知来源) 在 java.base/java.util.ArrayList$Itr.next(未知来源)

关于java - 如何解决数组列表中未知来源的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55905267/

相关文章:

javascript - 如何使用 for 循环调用对象内所有方法内的所有函数?

java - 要数组的多个对象

java - 数组列表的成本

java - 一个让我困惑的Android场景

java - BlueJ 的矩形类

java - 如何提高使用JDBC导入数据库的性能?

java - 我们应该在超时时使用 Thread.sleep( ) 吗?

java - 你能接受可变参数作为注释中的值吗?

r - 按日期范围和分类变量组合数据集

C++ 标准偏差函数?