[英]Remove last element of a list
I've been tasked to do the below in a newbie Java tutorial on ArrayList 我的任务是在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.
Below is my code 以下是我的代码
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));
}
}
}
The code runs, but I get the below error message when it runs. 代码运行,但运行时我收到以下错误消息。 Any ideas on what I'm doing wrong?
关于我做错了什么的任何想法?
java.util.Random@7852e922java.util.Random@4e25154fjava.util.Random@70dea4ejava.util.Random@5c647e05java.util.Random@33909752java.util.Random@55f96302java.util.Random@3d4eac69java.util.Random@42a57993java.util.Random@75b84c92java.util.Random@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
indices go from 0
to list.size() - 1
. List
索引从0
到list.size() - 1
。 Exceeding the upper bound results in the IndexOutOfBoundsException
超出上限会导致
IndexOutOfBoundsException
list.remove(list.size() - 1);
Your list has 11 elements, their indices are 0-10. 你的清单有11个元素,它们的索引是0-10。 When you call
list.remove(list.size());
当你调用
list.remove(list.size());
, you are telling it to remove the element at index 11 (because the size of the list is 11), but that index is out of bounds. ,你告诉它删除索引11处的元素(因为列表的大小是11),但该索引超出范围。
The index of the last element of any list is always list.size() - 1
. 任何列表的最后一个元素的索引总是
list.size() - 1
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.