gpt4 book ai didi

java arraylist indexOutOfBonds 异常原因

转载 作者:行者123 更新时间:2023-12-01 22:00:10 25 4
gpt4 key购买 nike

我正在尝试在数组列表的不同位置添加各种项目。我需要使用 arraylist,因为要读取的元素数量不清楚。

当我添加元素时,我收到了indexoutofbonds 异常。我知道如果索引大于 size() 我可能会得到异常。但由于我认为当我尝试添加比数组列表大小更多的元素时,大小会增加,为什么我会收到异常? array 和 arraylist 之间的区别在于 arraylist 是动态的并处理大小问题?我错了吗?

示例如下。我正在使用数组列表的数组列表。

arr.add(e1,new ArrayList<Integer>());

在这种情况下,e1 可能是 1,0,10001,4,540,100000

arraylist 不应该解决这个问题吗?

我的意思是我不想使用下面的方法。我需要元素之间有空格,以便程序读取数据时其他元素可以适应它们的位置。我不希望它们被移动,因为为上面的代码指定的 add 方法正在获取位置和元素。我不想将该项目添加到下一个可用位置。

arr.add(new ArrayList<Integer>());

任何帮助都会有用。或者您可以要求我使用 Java 中的另一种数据结构来帮助解决我的问题。

最佳答案

如果您指定要插入的索引,它会动态地为您处理。但如果你想在特定位置插入,你必须确定:

index >= 0 && index < size()

请参阅documentation :

Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

..

Throws:

IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())

关于java arraylist indexOutOfBonds 异常原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33667439/

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