Java.util.LinkedList 类

java.util.LinkedList.addAll()方法用于在指定位置插入指定集合的​​所有元素在列表中。该方法将指定位置处的当前元素(如果有)以及任何后续元素向右移动(增加它们的索引)。新元素将按照指定集合的​​迭代器返回的顺序出现在列表中。

语法

public boolean addAll(int index, Collection<? extends E> c)

这里,E 是容器维护的元素类型。

参数

index 指定需要插入集合第一个元素的索引号
c 指定包含需要添加到列表中的所有元素的集合。

返回值

如果列表因调用而更改,则返回 true,否则返回 false。

异常

如果索引超出范围,则抛出IndexOutOfBoundsException,即(index < 0 || index > size())。

抛出NullPointerException,如果指定的集合为 null。

示例:

在下面的示例中,java.util.LinkedList。 addAll()方法用于将LinkedListlist的所有元素插入LinkedListMyList中的指定位置。

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //创建链表
    LinkedList<Integer> MyList = new LinkedList<Integer>();
    LinkedList<Integer> list = new LinkedList<Integer>();

    //填充我的列表
    MyList.add(10);
    MyList.add(20);
    MyList.add(30);

    //填充列表
    list.add(100);
    list.add(200);

    //打印链表
    System.out.println("Before method call, MyList contains: " + MyList); 

    MyList.addAll(1, list);
    
    //打印链表
    System.out.println("After method call, MyList contains: " + MyList);      
  }
}

上述代码的输出将是:

Before method call, MyList contains: [10, 20, 30]
After method call, MyList contains: [10, 100, 200, 20, 30]