删除列表的最后一个元素

问题描述 投票:0回答:3

我的任务是在 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)
java arraylist
3个回答
31
投票

List
指数从
0
list.size() - 1
。超过上限会导致
IndexOutOfBoundsException

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

3
投票

您的列表有 11 个元素,它们的索引为 0-10。当您调用

list.remove(list.size());
时,您是在告诉它删除索引 11 处的元素(因为列表的大小是 11),但该索引超出了范围。

任何列表最后一个元素的索引始终为

list.size() - 1


0
投票

从Java 21开始,您现在可以使用removeLast()。

删除并返回该集合的最后一个元素(可选操作)。

https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/List.html#removeLast()

© www.soinside.com 2019 - 2024. All rights reserved.