java arraylist deepcopy

java arraylist deepcopy

To create a deep copy of an ArrayList in Java, you can use the clone() method of the ArrayList class to create a new ArrayList with a copy of the elements of the original list.

Here is an example of how to create a deep copy of an ArrayList:

import java.util.ArrayList;

public class ArrayListDeepCopyExample {

    public static void main(String[] args) {
        ArrayList<String> words = new ArrayList<>();
        words.add("hello");
        words.add("world");

        ArrayList<String> copy = (ArrayList<String>) words.clone();

        System.out.println("Original: " + words);
        System.out.println("Copy: " + copy);
    }
}
Source‮tual.www:‬turi.com

This code creates an ArrayList of strings called words and adds the elements "hello" and "world" to the list. It then creates a deep copy of the words list using the clone() method and assigns it to the copy variable.

The clone() method creates a new ArrayList with a copy of the elements of the original list. The elements themselves are not copied, only the references to the objects are copied, so the copy list and the words list still share the same objects.

Note that the clone() method is defined in the Object class, which is the superclass of all classes in Java. It creates a shallow copy of the object, which means that only the top-level object is copied and the references to the contained objects are shared between the original and the copy. To create a deep copy, you need to manually copy the contained objects as well.

Alternatively, you can use the ArrayList constructor to create a new ArrayList from an existing list:

ArrayList<String> copy = new ArrayList<>(words);

This code creates a new ArrayList called copy and initializes it with the elements of the words list. This creates a deep copy of the words list, because the elements are copied rather than shared.

Keep in mind that if the elements of the ArrayList are mutable, changes made to the elements in one list will be reflected in the other list as well, because the elements themselves are shared between the lists. To avoid this, you need to create a deep copy of the elements as well.

Created Time:2017-11-03 00:14:44  Author:lautturi