the code:
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");
}
}
result:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 1
I know I can just use .add("String")
to add anything I want in arraylist without caring about index. However, what I want is to add "String"
in specific index. Is there any way to do so without raising IndexOutOfBoundsException?
You can check if the index where you want the new String to be is OutOfBounds or not, for example:
ArrayList<String> temp = new ArrayList<String>();
temp.add(0,"123");
int index = 3;
if (temp.size() > index){
temp.add(index,"123");
}
When it is OutOfBounds you can create a larger ArrayList or add it to a lower indexNumber.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.