简体   繁体   English

如何在不提高IndexOutOfBoundsException的情况下按Java数组列表中的特定索引添加内容?

[英]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. 我知道我可以只使用.add("String")在arraylist中添加我想要的任何内容,而无需关心索引。 However, what I want is to add "String" in specific index. 但是,我想要在特定索引中添加"String" Is there any way to do so without raising IndexOutOfBoundsException? 有什么办法可以在不引发IndexOutOfBoundsException的情况下进行操作?

You can check if the index where you want the new String to be is OutOfBounds or not, for example: 您可以检查希望新String所在的索引是否为OutOfBounds,例如:

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. 当它是OutOfBounds时,您可以创建一个较大的ArrayList或将其添加到较低的indexNumber。

I would suggest for your propose to use a HashMap . 我建议您使用HashMap

It allows you to add key-value elements so you don't need to bother with IndexOutOfBoundsException. 它允许您添加键值元素,因此您无需费心IndexOutOfBoundsException。

A example on how to use it can be found here . 有关如何使用它的示例,请参见此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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