简体   繁体   中英

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

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.

I would suggest for your propose to use a HashMap .

It allows you to add key-value elements so you don't need to bother with IndexOutOfBoundsException.

A example on how to use it can be found here .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM