[Java development] Java object loop traversal assignment, the values are all the same and the value of the last object - problem solving

why this problem

In the development process of Java, when encountering some situations of copying objects and copying data, or encountering a loop operation based on the value of the old object and assigning a new value, the object value in the assigned object list will appear It's exactly the same, even the value of the last object.

Incorrect代码示例

        ProjectEntity projectEntity = this.selectById(id);
        List<ProjectEntity> projectEntities = new ArrayList<>();
        userIds.forEach(item->{
    
    
            projectEntity.setCreateBy(item);
            projectEntities.add(projectEntity);
        });
        this.insertBatch(projectEntities);

From the above code,
the first step: Find a basic object value from the database according to the id.
The second step: traverse the loop, modify the content of the createBy field of the object in turn, and write the first data into the first element of the list Inside...the second data is written into the second element...and so on
Step 3: End the loop and insert into the database in the form of a traversal operation

Result : the data inserted into the database is exactly the same, and they are all the values ​​of the last object

Cause analysis

Because only a memory address is specified before being placed in the for loop, the original data is overwritten on a memory address every time, so what you get is always the last value of the loop.
In other words, what is operated in the loop is only a reference, not a "value" as we understand it

Solution

1. In the loop body, each loop should first initialize a new object, that is to say, new the object again and let it obtain a new address

        userIds.forEach(item->{
    
    
        	ProjectEntity projectEntity = new ProjectEntity();
            projectEntity.setCreateBy(item);
            projectEntities.add(projectEntity);
        });
        this.insertBatch(projectEntities);

This method is correct, but I think it simply solves the problem, but does not solve the demand.
In fact, what we want more is to be able to retain the data of the objects obtained from the database, and modify the data based on it, and finally insert N pieces of new data into the database

reference answer

                //根据id获取方案基本信息
        ProjectEntity projectEntity = this.selectById(id);
        List<ProjectEntity> projectEntities = new ArrayList<>();
        userIds.forEach(item->{
    
    
            //初始化新的对象引用 使用hutool的实体内容复制
            ProjectEntity newProjectEntity= Convert.convert(ProjectEntity.class,projectEntity);
            newProjectEntity.setCreateBy(item);
            projectEntities.add(newProjectEntity);
        });
        this.insertBatch(projectEntities);

Guess you like

Origin blog.csdn.net/RayCongLiang/article/details/130266987