Copy Operations in Java ArrayList: Understanding Reference Behavior
Assigning a reference to a Java object, such as an ArrayList, simply copies the reference value, not the object itself. In the case of ArrayLists, assigning l1 to l2 means both references point to the same ArrayList object. Any subsequent changes made through l2 will also be reflected in l1.
However, there are scenarios where you may need a copy of the ArrayList object, not just a reference. To achieve this, you can create a new ArrayList object and populate it by copying elements from the original ArrayList using collection methods such as addAll(). This process creates a new ArrayList object with its own underlying data structure, making the copy independent of the original.
Code Example:
List<Integer> l1 = new ArrayList<>(); for (int i = 1; i <= 10; i++) { l1.add(i); } // Create a new ArrayList object to copy the elements into List<Integer> l2 = new ArrayList<>(); l2.addAll(l1); // Clear the original list using l2 l2.clear(); // Original list l1 remains unaffected System.out.println(l1); // Prints [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The above is the detailed content of How to Create a True Copy of a Java ArrayList: Reference vs. Independent Object?. For more information, please follow other related articles on the PHP Chinese website!