簡體   English   中英

如何在不提高IndexOutOfBoundsException的情況下按Java數組列表中的特定索引添加內容?

[英]How to add thing by specific index in arraylist in java without raise IndexOutOfBoundsException?

編碼:

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        ArrayList<String> temp = new ArrayList<String>();
        temp.add(0,"123");
        temp.add(3,"123");
    }
}

結果:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 1

我知道我可以只使用.add("String")在arraylist中添加我想要的任何內容,而無需關心索引。 但是,我想要在特定索引中添加"String" 有什么辦法可以在不引發IndexOutOfBoundsException的情況下進行操作?

您可以檢查希望新String所在的索引是否為OutOfBounds,例如:

ArrayList<String> temp = new ArrayList<String>();
    temp.add(0,"123");
    int index = 3;
    if (temp.size() > index){
        temp.add(index,"123");
    }

當它是OutOfBounds時,您可以創建一個較大的ArrayList或將其添加到較低的indexNumber。

我建議您使用HashMap

它允許您添加鍵值元素,因此您無需費心IndexOutOfBoundsException。

有關如何使用它的示例,請參見此處

暫無
暫無

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

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