Deep copy and shallow copy of Java-List<Map>

Blog background is Java development. Let’s talk about deep copy and shallow copy in List<Map> copying.

1. Shallow copy

Except for the basic type of Map, which is passed by value, the rest is passed by reference address.
Since the reference address of map's value storage is passed (list), when the internal properties of the list object change, the value in the map changes accordingly. This method is a shallow copy.

For example: list1 is shallow copied into list2. Arrays with the same content in Java point to the same address, that is, list1 and list2 after shallow copy point to the same address. The impact of this is that if list2 is changed, list1 will also be changed. Because changing list2 means changing the content of the address it points to, and list1 also points to the same address, so list1 and list2 will change together.

In the following code example, there are three ways to implement shallow copy:

1.1 Loop traversal copy

//方法一:循环遍历复制
List<Map<String, Object>> list2 = new ArrayList<>(list1.size());
for (Map<String, Object> map : list1) {
    
    
    listt2.add(map);
}

1.2 Use list to implement class construction method

//方法二:使用list实现类的构造方法
List<Map<String, Object>> list2 = new ArrayList<>(list1);

1.3 addAll method

//方法三:使用addAll
List<Map<String, Object>> list2 = new ArrayList<>();
list2.addAll(list1);

2. Deep copy

If you do not want to change the value in the original map, you can use the reflection principle to perform deep copy processing. The principle is to open up a new memory address in the memory, so the value at the old address will not be changed.

For example, deep copy copies list1 to list2, creates a new address for list2, and then transfers the contents of list1 address to list2 address. This will make the contents of list1 and list2 consistent, but since they point to different addresses, the changes will not affect each other.

Deep copy tool class SerializationUtils.clone

commons-lang-2.6.jar
例如:Object obj = SerializationUtils.clone( objectFrom )

The code example is as follows, implemented using the deep copy tool class

List<HashMap<String, Object>> list2 = new ArrayList<>();
for (Map<String, Object> hashMap : list1) {
    
    
    list2.add((HashMap<String, Object>) SerializationUtils.clone((Serializable) hashMap));
}

Reference:
https://blog.csdn.net/VIP099/article/details/108633345
https://blog.csdn.net/shy415502155/article/details/106048557/

Guess you like

Origin blog.csdn.net/weixin_44436677/article/details/132916180