gpt4 book ai didi

java - Container.remove(int i) 抛出意外的 ArrayIndexOutOfBoundsException

转载 作者:行者123 更新时间:2023-11-29 06:47:57 25 4
gpt4 key购买 nike

我正在尝试从 Java 容器中删除除第一个子组件之外的所有子组件。以下代码记录“There are 3”并抛出 ArrayIndexOutOfBoundsException: Array index out of range: 2

int componentCount = cardPanel.getComponentCount();
logger.info("There are " + componentCount);
for (int i = 1; i < componentCount; i++) {
cardPanel.remove(i);
}

但是,这个修改后的版本可以完美运行:

Component[] components = cardPanel.getComponents();
logger.info("There are " + components.length);
for (int i = 1; i < components.length; i++) {
cardPanel.remove(components[i]);
}

Container.getComponentCount() 和 Container.remove(int i) 似乎无法就容器中的组件数量达成一致。还有其他人遇到过这个问题吗?

最佳答案

当您执行 cardPanel.remove(i) 时,组件的数量正在减少。

所以你有 [0, 1, 2],并删除索引 1 处的项目。
现在您有 [0, 2] 并删除索引 2 处的项目,这会引发 ArrayIndexOutOfBoundsException。

修改后的版本有效,因为它从容器中删除了实际对象,而不是从索引中删除。

试试这个

int componentCount = cardPanel.getComponentCount();
logger.info("There are " + componentCount);
for (int i = 1; i < componentCount; i++) {
cardPanel.remove(1);
}

关于java - Container.remove(int i) 抛出意外的 ArrayIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1419745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com