How to backup ArrayList in Java?

后端 未结 10 1501
刺人心
刺人心 2020-12-09 12:40

I have some data stored as ArrayList. And when I want to backup this data,java bounds two objects forever. Which means when I change values in data ArrayL

10条回答
  •  悲哀的现实
    2020-12-09 12:58

    All of these processes make shallow copies. If you're changing properties of objects with in the array, the two arrays have references to the same instance.

    List org = new java.util.ArrayList();
    org.add(instance)
    org.get(0).setValue("org val");
    List copy = new java.util.ArrayList(org);
    org.get(0).setValue("new val");
    

    copy.get(0).getValue() will return "new val" as well because org.get(0) and copy.get(0) return the exact same instance. You have to perform a deep copy like so:

    List copy = new java.util.ArrayList();
    for(Instance obj : org) {
        copy.add(new Instance(obj)); // call to copy constructor
    }
    

提交回复
热议问题