[英]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.