繁体   English   中英

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

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

我建议您使用HashMap

它允许您添加键值元素,因此您无需费心IndexOutOfBoundsException。

有关如何使用它的示例,请参见此处

暂无
暂无

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

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