How to backup ArrayList in Java?

后端 未结 10 1477
刺人心
刺人心 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:54

    I haven't tried it yet, but I think Collections.copy will do that.

    [EDIT] Now, I tried:

    static String GetRandomString(int length)
    {
      UUID uuid = UUID.randomUUID();
      return uuid.toString().substring(0, length);  
    }
    
    public static void main(String[] args)
    {
      ArrayList<String> al = new ArrayList<String>(20);
      for (int i = 0; i < 10; i++)
      {
        al.add(GetRandomString(7));
      }
      ArrayList<String> cloneArray = new ArrayList<String>(al);
      Collections.copy(cloneArray, al);
      System.out.println(al);
      System.out.println(cloneArray);
      for (int i = 9; i >= 0; i -= 2)
      {
        al.remove(i);
      }
      System.out.println(al);
      System.out.println(cloneArray);
    }
    
    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 2020-12-09 13:02

    Depends what you need. Shallow copy (items in list are references to the same as in the original):

    ArrayList backup = new ArrayList(mylist.size());
    backup.addAll(mylist);
    

    Deep copy (items are copies also):

    ArrayList backup = new ArrayList(mylist.size());
    for(Object o : mylist) {
        backup.add(o.clone());
    }
    
    0 讨论(0)
  • 2020-12-09 13:04

    Your question isn't very clear. If you clone() an ArrayList, the clone will not be modified if you change the contents of the original (ie if you add or remove elements) but it's a "shallow copy" so if you change the actual objects in the original they will also be changed in the clone.

    If you want to make a "deep copy", so that changes to the actual objects will not affect the backups of them in the clone, then you need to create a new ArrayList and then go through the original one and for each element, clone it into the new one. As in

    ArrayList backup = new ArrayList();
    for (Object obj : data)
       backup.add(obj.clone());
    
    0 讨论(0)
提交回复
热议问题