Java ArrayList Object Referencing in Assignment
When an ArrayList l1 is assigned to a new reference l2, l1 and l2 do not point to different ArrayList objects. Instead, l2 receives a reference to the same ArrayList object as l1. This is known as shallow copy.
Modifying the list object through either l1 or l2 will be reflected in both references. As seen in the example:
List<Integer> l1 = new ArrayList<>(); for (int i = 1; i <= 10; i++) { l1.add(i); } List l2 = l1; l2.clear();
l1 and l2 both reference the same object, so clearing the list via l2 also affects l1.
To create a copy of the ArrayList object, a new list with a copy of the original elements should be created. One way to achieve this is using the ArrayList(Collection extends E> c) constructor, where c is the original collection:
List<Integer> newList = new ArrayList<>(l1);
This creates a new ArrayList object with a separate reference and copy of the elements from l1.
The above is the detailed content of How does assigning an ArrayList to a new reference affect the original object?. For more information, please follow other related articles on the PHP Chinese website!