如何在java中创建相同ArrayList的两个副本

时间:2015-07-28 18:21:18

标签: java list arraylist core

我正在尝试为备份目的创建列表副本,但是当我在原始列表中进行一些更改时,同样的更改也反映在副本列表中。 请找到以下代码供您参考

class ListElement{
    private String name;
    private Integer age;

    ListElement(String name, Integer age){
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
}


public class ListUnionTest {

    public static void main(String[] ars){

        ListElement ele = new ListElement("ABC", 25);
        List<ListElement> list_1 = new ArrayList<ListElement>();
        list_1.add(ele);

        System.out.println("Before ADDALL --> " + list_1.get(0).getAge());

        List<ListElement> list_2 = new ArrayList<ListElement>();
        list_2.addAll(list_1);

        System.out.println("AFTER ADDALL --> " + list_2.get(0).getAge());

        list_1.get(0).setAge(30);

        System.out.println("after change in List_1  orginal list value  --> " + list_1.get(0).getAge());
        System.out.println("after change List_1 copy list value --> " + list_2.get(0).getAge());

    }
}

Actual output:
Before ADDALL --> 25
AFTER ADDALL --> 25
after change in List_1  orginal list value --> 30
after change List_1 copy list value --> 30


Expected output:
Before ADDALL --> 25
AFTER ADDALL --> 25
after change in List_1  orginal list value --> 30
after change List_1 copy list value --> 25

因此我丢失了旧数据。

0 个答案:

没有答案