在这个例子中,我们将看到如何从LinkedList
中删除一个元素。
示例
我们将使用LinkedList
类的remove(int index)
方法从特定索引中删除元素。方法定义和描述如下:
public E remove(int index)
:删除此列表中指定位置的元素。将任何后续元素向左移位(从索引中减去一个)。返回从列表中删除的元素。
import java.util.LinkedList;
public class RemoveFromLinkedList {
public static void main(String[] args) {
// Create a LinkedList
LinkedList<String> linkedlist = new LinkedList<String>();
// Add elements to LinkedList
linkedlist.add("Cobol");
linkedlist.add("JCL");
linkedlist.add("C++");
linkedlist.add("C#");
linkedlist.add("Java");
// Displaying Elements before replace
System.out.println("LinkedList Elements:");
for(String str: linkedlist){
System.out.println(str);
}
// Removing 3rd element
Object e1 = linkedlist.remove(2);
System.out.println("\nElement "+ e1+ " removed from the list\n");
// LinkedList elements after remove
System.out.println("After removal:");
for(String str2: linkedlist){
System.out.println(str2);
}
}
}
输出:
LinkedList Elements:
Cobol
JCL
C++
C#
Java
Element C++ removed from the list
After removal:
Cobol
JCL
C#
Java