Java 删除列表的最后一个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27850903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 05:09:06  来源:igfitidea点击:

Remove last element of a list

javaarraylist

提问by Kenneth Yong

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?

代码运行,但我在运行时收到以下错误消息。关于我做错了什么的任何想法?

[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)

采纳答案by Reimeus

Listindices go from 0to list.size() - 1. Exceeding the upper bound results in the IndexOutOfBoundsException

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

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

回答by Zoltán

Your list has 11 elements, their indices are 0-10. When you call 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 个元素,它们的索引为 0-10。当您调用 时list.remove(list.size());,您是在告诉它删除索引 11 处的元素(因为列表的大小为 11),但该索引超出范围。

The index of the last element of any list is always list.size() - 1.

任何列表的最后一个元素的索引总是list.size() - 1