Java Arraylist 得到 java.lang.IndexOutOfBoundsException?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18446302/
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
Java Arraylist got java.lang.IndexOutOfBoundsException?
提问by Vittori
I'm a general 3D artist, switched from my career and started to learn programming. I've got a problem with c106a handout #5.
我是一名普通的 3D 艺术家,从我的职业生涯转向并开始学习编程。我的 c106a 讲义 #5 有问题。
The code works, but I've still got some error log here.
代码有效,但我这里仍然有一些错误日志。
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 4
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.get(ArrayList.java:322)
at UniqueNames.showUnique(UniqueNames.java:23)
at UniqueNames.main(UniqueNames.java:39)
Why does Arraylist
, which can stretch its capacity on its own, still get an OutOfBoundsException
?
为什么Arraylist
可以自行扩展容量的 ,仍然得到OutOfBoundsException
?
Here's my full code:
这是我的完整代码:
import acm.io.*;
import acm.program.ConsoleProgram;
import acm.util.*;
import java.io.*;
import java.util.ArrayList;
import java.lang.*;
public class UniqueNames extends ConsoleProgram{
static ArrayList<String> meString = new ArrayList<String>();
static String input ;
public static void storeUnique(String input){
if (!meString.contains(input))
{
meString.add(input);
}
}
public static void showUnique(ArrayList<String> meString){
System.out.println("Unique name list contains:");
for(int i=0 ;i<= meString.size() ;i++){
System.out.println(meString.get(i));
}
}
public static void main(String[] args){
try{
InputStreamReader stream = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(stream);
while (true){
System.out.println("Enter name:");
String input = br.readLine();
if (input.equals("")) break;
storeUnique(input);
}
{showUnique(meString);}
}
catch(IOException e){
}
}
}
回答by Suresh Atta
The following lines:
以下几行:
for (int i = 0; i <= meString.size(); i++) {
System.out.println(meString.get(i));
}
should be:
应该:
for (int i = 0; i < meString.size(); i++) {
System.out.println(meString.get(i));
}
This is because the index of the list starts from zero.
这是因为列表的索引从零开始。
Index: 4, Size: 4
explains a little more. When you call get(4)
, an exception occurs because your list only has a size of 4. get(4)
would attempt to access the 5th element in the list.
Index: 4, Size: 4
再解释一下。当您调用 时get(4)
,会发生异常,因为您的列表只有 4 的大小。get(4)
将尝试访问列表中的第 5 个元素。
Valid elements you can access would be get(0)
, get(1)
, get(2)
, get(3)
.
您可以访问的有效元素是get(0)
, get(1)
, get(2)
, get(3)
。
回答by Ankit
Use the above answer, or you can use a foreach loop:
使用上面的答案,或者您可以使用foreach 循环:
for (String str: meString) {
System.out.println(str);
}
回答by James Dunn
You asked, "Why does Arraylist, which can stretch its capacity by its own still get an OutOfBoundsException ???"
The answer is: an ArrayList only stretches its capacity when:
你问,“为什么可以自行扩展容量的 Arraylist 仍然得到 OutOfBoundsException ???”
答案是:ArrayList 仅在以下情况下扩展其容量:
- You add an object to it (
.add(Object o)
). - You add the contents of another collection to it (
.addAll(Collection c)
). - You ensure its size (
.ensureCapacity(int minCapacity)
).
- 您向其添加一个对象 (
.add(Object o)
)。 - 您将另一个集合的内容添加到它 (
.addAll(Collection c)
)。 - 您确保其大小 (
.ensureCapacity(int minCapacity)
)。
The trouble you're having is that you are trying to access an object in an index of the list that doesn't exist. While an ArrayList will dynamically resize when you changethe contents, it won't do it when you are simply trying to accessthe contents.
That is the difference.
To avoid accessing an index that doesn't exist:
您遇到的问题是您试图访问不存在的列表索引中的对象。虽然当您更改内容时 ArrayList 会动态调整大小,但当您只是尝试访问内容时它不会这样做。
这就是区别。
为避免访问不存在的索引:
- Take Surresh Atta's suggestion: Use
i < meString.size()
instead ofi <= meString.size()
because the index starts with 0 instead of 1. - Take Ankit's suggestion and just use the enhanced for loop:
for(String str : meString)
.
- 接受 Surresh Atta 的建议:使用
i < meString.size()
而不是i <= meString.size()
因为索引从 0 开始而不是 1。 - 就拿ANKIT的建议,只是使用增强的for循环:
for(String str : meString)
。
回答by Harish Chandrasekaran
If you are using a 2D ArrayList ,make sure you instantiate every row and every element of the corresponding row using the following code:
如果您使用的是 2D ArrayList ,请确保使用以下代码实例化每一行和相应行的每个元素:
for(int i=0;i<n;i++)
{
p.add(new ArrayList<Integer>());
for(int j=0;j<n;j++)
{
p.get(i).add(new Integer(0));
}
}
This creates an ArrayList with i (=n) rows and each row contains an ArrayList with j (=n) number of elements.
这将创建一个具有 i (=n) 行的 ArrayList,每行包含一个具有 j (=n) 个元素的 ArrayList。
If instantiation is not done properly it might result in an IndexOutOfBoundsException
如果未正确完成实例化,则可能会导致 IndexOutOfBoundsException