簡體   English   中英

刪除列表的最后一個元素

[英]Remove last element of a list

我的任務是在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);

你的清單有11個元素,它們的索引是0-10。 當你調用list.remove(list.size()); ,你告訴它刪除索引11處的元素(因為列表的大小是11),但該索引超出范圍。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM