原文: https://beginnersbook.com/2014/08/clone-a-generic-linkedlist-in-java/

示例

  1. import java.util.LinkedList;
  2. class LinkedListClone {
  3. public static void main(String[] args) {
  4. // create a LinkedList
  5. LinkedList<String> list = new LinkedList<String>();
  6. // Adding elements to the LinkedList
  7. list.add("Element1");
  8. list.add("Element2");
  9. list.add("Element3");
  10. list.add("Element4");
  11. // Displaying LinkedList elements
  12. System.out.println("LinkedList elements: "+list);
  13. // Creating another list
  14. LinkedList<String> list2 = new LinkedList<String>();
  15. // Clone list to list2
  16. /* public Object clone(): Returns a shallow copy of this
  17. * LinkedList. (The elements themselves are not cloned.)
  18. */
  19. list2 = (LinkedList)list.clone();
  20. // Displaying elements of second LinkedList
  21. System.out.println("List 2 Elements: "+list2);
  22. }
  23. }

输出:

  1. LinkedList elements: [Element1, Element2, Element3, Element4]
  2. List 2 Elements: [Element1, Element2, Element3, Element4]