![](/img/trans.png)
[英]Java ArrayList IndexOutOfBoundsException Index: 1, Size: 1
[英]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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.