代码:
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")
在不关心索引的情况下添加我想要的任何我想要的东西。但是,我想要的是在特定索引中添加"String"
。有什么办法可以这样做,而不会提高indexoutofboundsexception?
我建议您使用hashmap。
它允许您添加键值元素,因此您无需打扰indexoutofBoundSexception。
可以在此处找到有关如何使用它的示例。
您可以检查您是否希望新字符串的索引是外面的,例如:
ArrayList<String> temp = new ArrayList<String>();
temp.add(0,"123");
int index = 3;
if (temp.size() > index){
temp.add(index,"123");
}
当它变外时,您可以创建一个较大的arraylist或将其添加到较低的indexnumber中。