Java 即使索引在范围内,从 ArrayList 检索第 N 个项目也会给出 IndexOutOfBoundsException?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19730506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Retrieve Nth item from ArrayList gives IndexOutOfBoundsException even when index is in range?
提问by user1902535
I have an ArrayList and I am trying to measure the time it takes to retrieve an item from the middle of my ArrayList.
我有一个 ArrayList,我试图测量从我的 ArrayList 中间检索一个项目所需的时间。
Here it is:
这里是:
List<Car> cars = new ArrayList<Car>();
for (int i = 0; i < 1000000; i++) {
cars.add(new Car(null, i));
How would I retrieve item 500000?
我将如何检索项目 500000?
I tried creating a variable like int example = 500000, then put cars.get(example). But I just got errors:
我尝试创建一个像 int example = 500000 这样的变量,然后把 cars.get(example)。但我只是有错误:
java.lang.IndexOutOfBoundsException: Index: 500000, Size: 1
java.lang.IndexOutOfBoundsException:索引:500000,大小:1
Here why am I getting an IndexOutOfBoundsException even when the index I requested < total entries?
在这里,为什么即使我请求的索引 < 总条目数,我也会收到 IndexOutOfBoundsException?
Any help would be appreciated. Thanks.
任何帮助,将不胜感激。谢谢。
回答by Math
Use the get()
function
使用get()
功能
cars.get(500000);
EDIT
编辑
IndexOutOfBoundsException
means you are trying to retrieve an information that is beyond the list.
IndexOutOfBoundsException
表示您正在尝试检索列表之外的信息。
Your error is not related to the function you're using, you are probably making a mistake somewhere else. Please realize whether you're populating and trying to read from the same variable.
您的错误与您使用的功能无关,您可能在其他地方犯了错误。请意识到您是否正在填充并尝试从同一个变量中读取。
回答by aglassman
Your list is named car, but you are adding to a list named cars.
您的列表名为 car,但您要添加到名为 cars 的列表中。
回答by rolfl
If you want to create an indexed collection of data you would likely want to use something other than an ArrayList.... consider a HashMap for example:
如果你想创建一个索引的数据集合,你可能想要使用 ArrayList 以外的东西......考虑一个 HashMap 例如:
HashMap<Integer, Car> map = new HashMap<>();
for (int i = 0; i < 1000000; i++) {
map.put(i, new Car(null, i));
}
Car c = map.get(500000);