SoFunction
Updated on 2025-03-08

Example code of 8 shallow copy methods of ArrayList in Java

introduction

Hi, friends! Today, let’s talk about the shallow copy of ArrayList in Java. What is a shallow copy? Simply put, when copying an object, it only copies the reference to the object, and does not copy the object itself. So, how to make a shallow copy of ArrayList in Java? Don't worry, let's start revealing the secret now!

What is a shallow copy?

Shallow copy means that when copying an object, it only copies the reference address of the object, and not the object itself. Therefore, the original object and the copy object share the same copy of data. In Java, when we make a shallow copy of the ArrayList, we simply copy the reference to the element in the ArrayList, not the element itself.

The importance of a shallow copy

In daily development, we often need to operate on ArrayList without affecting the original collection. At this time, shallow copies can come in handy. Let’s take a look at eight ways to implement shallow copying!

Method 1: Use the constructor

Use the ArrayList constructor to create a new ArrayList and pass the original ArrayList as an argument.

List<String> originalList = new ArrayList<>(("apple", "banana", "cherry"));
List<String> shallowCopy = new ArrayList<>(originalList);

Method 2: Use the addAll() method

A shallow copy is achieved by adding all elements of the original ArrayList to the new ArrayList.

List<String> originalList = new ArrayList<>(("apple", "banana", "cherry"));
List<String> shallowCopy = new ArrayList<>();
(originalList);

Method 3: Use ()

Although this method is usually used for array copying, we can first convert the ArrayList to an array, then copy it, and finally convert it back to an ArrayList.

List<String> originalList = new ArrayList<>(("apple", "banana", "cherry"));
String[] array = (new String[0]);
String[] shallowCopyArray = new String[];
(array, 0, shallowCopyArray, 0, );
List<String> shallowCopy = new ArrayList<>((shallowCopyArray));

Method 4: Use ()

This method is very convenient, use directly()The method can complete the shallow copy.

List<String> originalList = new ArrayList<>(("apple", "banana", "cherry"));
List<String> shallowCopy = new ArrayList<>(());
(shallowCopy, originalList);

Method 5: Use Java 8 Stream API

Starting in Java 8, the Stream API provides a cleaner way to implement shallow copying.

List<String> originalList = new ArrayList<>(("apple", "banana", "cherry"));
List<String> shallowCopy = ().collect(());

Method 6: Use clone() method

If ArrayList is implementedCloneableInterface, we can use it directlyclone()method.

List<String> originalList = new ArrayList<>(("apple", "banana", "cherry"));
List<String> shallowCopy = null;
try {
    shallowCopy = (List<String>) ();
} catch (CloneNotSupportedException e) {
    // Handle exception
}

Notice:ArrayListThe class is implemented by defaultCloneableInterface, soclone()The method can be used directly.

Method 7: Use the method ()

If the original ArrayList contains basic types or immutable objects, we can use them directly()method.

List<Integer> originalList = (1, 2, 3);
List<Integer> shallowCopy = new ArrayList<>((()));

Method 8: Use the Guava library

The Guava library provides practical collection tool classesLists, can easily achieve shallow copy.

List<String> originalList = new ArrayList<>(("apple", "banana", "cherry"));
List<String> shallowCopy = (originalList);

Walkthrough steps

Let's take a specific example to learn more about these shallow copies.

Sample code

Suppose we have an original ArrayListoriginalList, we will use the above method to make a shallow copy of it.

import .*;

public class ArrayListShallowCopyDemo {

    public static void main(String[] args) {
        List&lt;String&gt; originalList = new ArrayList&lt;&gt;(("apple", "banana", "cherry"));

        // Method 1: Use constructor        List&lt;String&gt; shallowCopy1 = new ArrayList&lt;&gt;(originalList);

        // Method 2: Use addAll()        List&lt;String&gt; shallowCopy2 = new ArrayList&lt;&gt;();
        (originalList);

        // Method 3: Use ()        String[] array = (new String[0]);
        String[] shallowCopyArray = new String[];
        (array, 0, shallowCopyArray, 0, );
        List&lt;String&gt; shallowCopy3 = new ArrayList&lt;&gt;((shallowCopyArray));

        // Method 4: Use ()        List&lt;String&gt; shallowCopy4 = new ArrayList&lt;&gt;(());
        (shallowCopy4, originalList);

        // Method 5: Use Java 8 Stream API        List&lt;String&gt; shallowCopy5 = ().collect(());

        // Method 6: Use clone()        List&lt;String&gt; shallowCopy6 = null;
        try {
            shallowCopy6 = (List&lt;String&gt;) ();
        } catch (CloneNotSupportedException e) {
            // Handle exception
        }

        // Method 7: Use () (Applicable to basic types or immutable objects)        List&lt;Integer&gt; originalIntList = (1, 2, 3);
        List&lt;Integer&gt; shallowCopy7 = new ArrayList&lt;&gt;((()));

        // Method 8: Use the Guava library        List&lt;String&gt; shallowCopy8 = (originalList);

        // Output the copied list        ("Original List: " + originalList);
        ("Shallow Copy 1: " + shallowCopy1);
        ("Shallow Copy 2: " + shallowCopy2);
        ("Shallow Copy 3: " + shallowCopy3);
        ("Shallow Copy 4: " + shallowCopy4);
        ("Shallow Copy 5: " + shallowCopy5);
        ("Shallow Copy 6: " + shallowCopy6);
        ("Shallow Copy 7: " + shallowCopy7);
        ("Shallow Copy 8: " + shallowCopy8);
    }
}

Running results

After running the above program, we can see that all copied lists contain the data of the original list.

Performance comparison

Each shallow copy method has its applicable scenarios. For example, use a constructor oraddAll()The method is the easiest and easy to understand; and use()or()It may be more efficient in some cases; using Java 8's Stream API provides a cleaner syntax.

Actual case analysis

Let's take a practical performance test to see the effects of different shallow copy methods.

Sample code

Suppose we have an ArrayList with a large amount of data, we will compare the performance differences between different shallow copy methods.

Summarize

Through the above examples, we can summarize:

  • Different shallow copy methods have their own advantages and disadvantages, and choosing the appropriate method depends on the specific application scenario.
  • Use constructor oraddAll()The method is the easiest and most direct way.
  • Using the Java 8 Stream API or the Guava library can make your code look more modern.

Interactive question

How do you implement a shallow copy of ArrayList in your project? Which method do you prefer? Welcome to share your experience in the comment section!

appendix

In actual use, the following points need to be considered:

  • Performance considerations: For large lists, some methods may be more efficient.
  • Memory consumption: Shallow copy does not add additional object memory consumption.
  • Object Type: For variable objects, shallow copies can cause unexpected side effects.

appendix

To further understand the process of shallow copying, we can use tools to aid in analysis, such as using Java Profiler to monitor memory usage, and using the JUnit test framework for performance testing.

Conclusion

I hope this article can help you better understand and apply the shallow copy method of ArrayList in Java.

This is the end of this article about 8 shallow copying methods of ArrayList in Java. For more related content on the shallow copying methods of ArrayList in Java, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!