Regarding the duplication of map data stored in the list

The data stored in the following two pieces of code are different
public static void main(String[] args) {
		List list = new ArrayList();
		list.add("a");
		list.add("b");
		list.add("c");
		// 第一组
		List list1 = new ArrayList();
		Map map = new HashMap<String, String>();
		for (int i = 0; i < list.size(); i++) {
			map.put("测试", list.get(i));
			list1.add(map);
		}
		for (int j = 0; j < list1.size(); j++) {
			System.out.println(list1.get(j)+"---");
		}
		// 第二组
		List list2 = new ArrayList();
		for (int i = 0; i < list.size(); i++) {
			Map map2 = new HashMap<String, String>();
			map2.put("测试", list.get(i));
			list2.add(map2);
		}
		for (int j = 0; j < list2.size(); j++) {
			System.out.println(list2.get(j)+"***");
		}
	}

The output of the first group is:

{Test=c}---

{Test=c}---

{Test=c}---

The output of the second group is:

{Test=a}***
{Test=b}***
{Test=c}***

We found that the output data of the two groups is not connected, just because the location of the map is different.

In the first set of codes, the list stores a map object, and the map points to the same address in the heap memory. In this case, data duplication or overwriting will occur;

In the second group, we put the map into the loop, so that a map object will be re-instantiated every time the loop is looped, so that the map object points to a different address in the heap memory, so the output data is also different of.

Guess you like

Origin blog.csdn.net/u013804636/article/details/60869587