gpt4 book ai didi

java - 删除列表的最后一个元素

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:39:46 33 4
gpt4 key购买 nike

我的任务是在有关 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));
}
}
}

代码运行,但运行时出现以下错误消息。对我做错了什么有什么想法吗?

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 索引从 0list.size() - 1。超过上限会导致 IndexOutOfBoundsException

list.remove(list.size() - 1);

关于java - 删除列表的最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27850903/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com