我受命在ArrayList上的Java新手教程中执行以下操作
// 1) Declare am ArrayList of strings
// 2) Call the add method and add 10 random strings
// 3) Iterate through all the elements in the ArrayList
// 4) Remove the first and last element of the ArrayList
// 5) Iterate through all the elements in the ArrayList, again.
下面是我的代码
import java.util.ArrayList;
import java.util.Random;
public class Ex1_BasicArrayList {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i <= 10; i++){
Random rand = new Random();
String randy = String.valueOf(rand);
list.add(randy );
}
for (int i = 0; i < list.size(); i++){
System.out.print(list.get(i));
}
list.remove(0);
list.remove(list.size());
for (int i = 0; i < list.size(); i++){
System.out.print(list.get(i));
}
}
}
该代码运行,但运行时出现以下错误消息。关于我在做什么错的任何想法吗?
[email protected]@[email protected]@[email protected]@[email protected]@[email protected]@6bc7c054Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 10, Size: 10
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.remove(Unknown Source)
at apollo.exercises.ch08_collections.Ex1_BasicArrayList.main(Ex1_BasicArrayList.java:23)
List
索引从0
到list.size() - 1
。超出上限将导致IndexOutOfBoundsException
list.remove(list.size() - 1);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句