Java Arraylist 得到 java.lang.IndexOutOfBoundsException? [英] Java Arraylist got java.lang.IndexOutOfBoundsException?
问题描述
我是一名普通的 3D 艺术家,从我的职业生涯开始学习编程.我的 c106a 讲义 #5 有问题.
I'm a general 3D artist, switched from my career and started to learn programming. I've got a problem with c106a handout #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)
为什么可以自行扩展容量的Arraylist
仍然得到OutOfBoundsException
?
Why does Arraylist
, which can stretch its capacity on its own, still get an OutOfBoundsException
?
这是我的完整代码:
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){
}
}
}
推荐答案
以下几行:
for (int i = 0; i <= meString.size(); i++) {
System.out.println(meString.get(i));
}
应该是:
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
稍微解释一下.当您调用 get(4)
时,会发生异常,因为您的列表只有 4 的大小.get(4)
将尝试访问列表中的第 5 个元素.
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.
您可以访问的有效元素是 get(0)
、get(1)
、get(2)
、get(3)
.
Valid elements you can access would be get(0)
, get(1)
, get(2)
, get(3)
.
这篇关于Java Arraylist 得到 java.lang.IndexOutOfBoundsException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!