gpt4 book ai didi

java - 添加到空 ArrayList 的中间?

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

如果我创建一个新的大小为 5 的数组列表...

    Player P;
ArrayList<Player> orderedPlayers = new ArrayList<Player>(5);

然后我尝试添加到那个数组列表的中间......

    orderedPlayers.add(2, P);

我得到一个 indexoutofbounds...如果我使用 set 而不是 add...我也会得到 indexoutofbounds...

    orderedPlayers.set(2, P);

事实上,我可以将 P 添加到数组列表的唯一方法是使用 0 索引...

    orderedPlayers.add(0, P);

还有一些奇怪的原因,当我这样做时,我在 eclipse 中的调试器看到该元素被添加到 orderedPlayers 的第 4 个索引而不是第 0 个...是 ArrayList 有问题还是我完全遗漏了什么?我将如何添加到空 ArrayList 的中间?

最佳答案

5是初始容量,不是实际大小。您不能添加到空数组列表的中间。

关于java - 添加到空 ArrayList 的中间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3578007/

25 4 0