void add(int index,Object element):此方法在列表中的指定索引处插入元素。它将当前位于该位置的元素(如果有)和任何后续元素右移(将在其索引处增加一个)。
用法:
void add(int index, Object element)
参数:该方法接受两个参数,如下所述。
index:要插入指定元素的索引。
element:需要插入的元素。
返回值:此方法不返回任何值。
异常:
Throws IndexOutOfBoundsException if the specified
index is out of range (index size()).
例:
// Java code to illustrate boolean add(Object element)
import java.io.*;
import java.util.LinkedList;
public class LinkedListDemo {
public static void main(String args[]) {
// creating an empty LinkedList
LinkedList list = new LinkedList();
// use add() method to add elements in the list
list.add("Geeks");
list.add("for");
list.add("Geeks");
list.add("10");
list.add("20");
// Output the present list
System.out.println("The list is:" + list);
// Adding new elements to the end
list.add(2, "Hello");
list.add(4, "End");
// printing the new list
System.out.println("The new List is:" + list);
}
}
输出:
The list is:[Geeks, for, Geeks, 10, 20]
The new List is:[Geeks, for, Hello, Geeks, End, 10, 20]