Java 8 list copy

See English answers > how to clone ArrayList and also clone its contents? 17

I can't update the employee object

public class Employee {

    public Employee(Integer id,Integer age,String gender,String fName,String lName) {
        this.id = id;
        this.age = age;
        this.gender = gender;
        this.firstName = fName;
        this.lastName = lName;
    }

    private Integer id;
    private Integer age;
    private String gender;
    private String firstName;
    private String lastName;

I initially set up an employee list, but I want to create a copy of it and change it Even if I'm creating a new list, it's still changing the original list

public class ListTest {

    public static void main(String[] args) {

        List<Employee> employeeList = new ArrayList<>();
        Employee employee = new Employee(1,1,"MALE","TEST","TEST");
        employeeList.add(employee);

        List<Employee> listTwo = new ArrayList<>();
        listTwo.addAll(employeeList);

        listTwo.get(0).setAge(11);

        System.out.println(employeeList.get(0).getAge());

    }
}

The output is 11

Is there a simpler way to clone from the original list, and any changes should not be applied to the original list object and the new list I created

Solution

It will not change the original list, but it is changing the objects contained in both lists

In this case, it may be useful to make the employee object immutable and provide the possibility to create a duplicate object with changed properties relative to the original properties

I'm not sure if clone () creates a deep copy of the object If so, all is fine. If not, you can use streams to create a deep copy

If you absolutely cannot modify the employee object (even without adding a copy constructor), you can do this:

public static Employee clone(Employee original) {
    return new Employee(original.getID(),original.getAge(),original.getGender(),original.getFirstName(),original.getLastName());
}

so what

employeeList.stream().map(item -> clone(item)).collect(Collectors.toList());

Or

employeeList.stream().map(<thisclassname>::clone).collect(Collectors.toList());

(basically the same as that suggested by uata, but you can copy it yourself)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>