java list.add(int index, String element)采坑记

官方API:
void java.util.List.add(int index, String element)

Inserts the specified element at the specified position in this list (optional operation). Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).
Parameters:
index index at which the specified element is to be inserted
element element to be inserted

描述是在指定的index插入一个元素,如果存在元素则将之前元素后移。
但是需要注意的是,如果超出当前list的index序列,会报IndexOutOfBoundsException异常:

简单的测试代码:
public static void main(String[] args)
{
    List<String> list = new ArrayList<>();
    list.add(0, "1");
    list.add(1, "2");
    list.add(3, "3");
    System.out.println(list);
}

在第6行执行时就会报错,因此如果在循环中调用add(e,v)的时候,如果出异常一定要处理index的问题,否则后续的结果都会报IndexOutOfBoundsException而导致没有加入到list当中。


评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据