原文: https://beginnersbook.com/2014/07/java-get-sub-list-from-linkedlist-example/

示例

在这个例子中,我们使用LinkedList类的subList(int startIndex, int endIndex)方法获取LinkedList的子列表。它返回指定索引startIndex(包括)和endIndex(不包括)之间的List。对子列表所做的任何更改都将反映在原始列表中(我们在下面的程序中通过从子列表中删除元素并在删除后显示原始列表来测试它)。

  1. import java.util.LinkedList;
  2. import java.util.Iterator;
  3. import java.util.List;
  4. public class SublistExample {
  5. public static void main(String[] args) {
  6. // Create a LinkedList
  7. LinkedList<String> linkedlist = new LinkedList<String>();
  8. // Add elements to LinkedList
  9. linkedlist.add("Item1");
  10. linkedlist.add("Item2");
  11. linkedlist.add("Item3");
  12. linkedlist.add("Item4");
  13. linkedlist.add("Item5");
  14. linkedlist.add("Item6");
  15. linkedlist.add("Item7");
  16. // Displaying LinkedList elements
  17. System.out.println("LinkedList elements:");
  18. Iterator it= linkedlist.iterator();
  19. while(it.hasNext()){
  20. System.out.println(it.next());
  21. }
  22. // Obtaining Sublist from the LinkedList
  23. List sublist = linkedlist.subList(2,5);
  24. // Displaying SubList elements
  25. System.out.println("\nSub List elements:");
  26. Iterator subit= sublist.iterator();
  27. while(subit.hasNext()){
  28. System.out.println(subit.next());
  29. }
  30. /* Any changes made to Sub List will be reflected
  31. * in the original List. Lets take this example - We
  32. * are removing element "Item4" from sublist and it
  33. * should be removed from original list too. Observe
  34. * the Output of this part of the program.
  35. */
  36. sublist.remove("Item4");
  37. System.out.println("\nLinkedList elements After remove:");
  38. Iterator it2= linkedlist.iterator();
  39. while(it2.hasNext()){
  40. System.out.println(it2.next());
  41. }
  42. }
  43. }

输出:

  1. LinkedList elements:
  2. Item1
  3. Item2
  4. Item3
  5. Item4
  6. Item5
  7. Item6
  8. Item7
  9. Sub List elements:
  10. Item3
  11. Item4
  12. Item5
  13. LinkedList elements After remove:
  14. Item1
  15. Item2
  16. Item3
  17. Item5
  18. Item6
  19. Item7