How to deep copy or shadow copy/clone a Collection(List/Set/Map)
This post would demo how to deep copy or shadow copy/clone a Collection(List/Set/Map).
This example will include:
Shadow copy of the Collection
Deep copy of the Collection
Because java always pass value to method parameters(When you mean pass by reference, it’s just the value of the object address). So if you pass a collection to a method, then its pointer(reference) would be passed to the method. So ,if you change the collection, the original collection would also be changed.
2.1 The Game class
I define a Game class for test. It’s just a simple pojo.
2.2 The util methods
We define a method to process a Collection of Games
Here we use a Functional parameter Consumer to process the games collection.And then use the stream’s forEach method to process the items.
2.3 The shadow copy
If we just pass a collection reference to a method,then the param collection and the original list share the same real instance. Only the pointer value is copied.
We can test like this:
We define a list of games and init with two instances of games
we pass the original collection to the util method processGame
As you can see, the original list is affected by the change.
2.4 Deep copy(clone)
If you want the collection stay unchanged after passing it to a method, you should deep copy it.
Firstly, add a constructor to the Game class for cloning purpose
This constructor only copy values from the old instance. Note the manu and the name is String, so it’s immutable, If the util method changes it, a new instance of String would be created, the original would not be affected.
Then we define a clone util method to clone a Collection like this:
As you can see, it just call the Game constructor we just added.
Thirdly, test it.
*line 1 changed the name of the game instance
line 2 Before pass to util method, we called the cloneList to clone it
Run the code, we got this
We can see that the original list is NOT affected by the util method.
In this post we demo how to do deep clone with Collections.You can find the whole code examples on github.
You can find detail documents about the java clone here: