原文: https://beginnersbook.com/2014/07/java-remove-element-from-a-specific-index-in-linkedlist-example/

在这个例子中,我们将看到如何从LinkedList中删除一个元素。

示例

我们将使用LinkedList类的remove(int index)方法)从特定索引中删除元素。方法定义和描述如下:

public E remove(int index):删除此列表中指定位置的元素。将任何后续元素向左移位(从索引中减去一个)。返回从列表中删除的元素。

  1. import java.util.LinkedList;
  2. public class RemoveFromLinkedList {
  3. public static void main(String[] args) {
  4. // Create a LinkedList
  5. LinkedList<String> linkedlist = new LinkedList<String>();
  6. // Add elements to LinkedList
  7. linkedlist.add("Cobol");
  8. linkedlist.add("JCL");
  9. linkedlist.add("C++");
  10. linkedlist.add("C#");
  11. linkedlist.add("Java");
  12. // Displaying Elements before replace
  13. System.out.println("LinkedList Elements:");
  14. for(String str: linkedlist){
  15. System.out.println(str);
  16. }
  17. // Removing 3rd element
  18. Object e1 = linkedlist.remove(2);
  19. System.out.println("\nElement "+ e1+ " removed from the list\n");
  20. // LinkedList elements after remove
  21. System.out.println("After removal:");
  22. for(String str2: linkedlist){
  23. System.out.println(str2);
  24. }
  25. }
  26. }

输出:

  1. LinkedList Elements:
  2. Cobol
  3. JCL
  4. C++
  5. C#
  6. Java
  7. Element C++ removed from the list
  8. After removal:
  9. Cobol
  10. JCL
  11. C#
  12. Java