Home > Java > javaTutorial > How to Create a True Copy of a Java ArrayList: Reference vs. Independent Object?

How to Create a True Copy of a Java ArrayList: Reference vs. Independent Object?

Mary-Kate Olsen
Release: 2024-11-16 05:31:03
Original
755 people have browsed it

How to Create a True Copy of a Java ArrayList: Reference vs. Independent Object?

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]
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template