How to backup ArrayList in Java?

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

    Here is a fully functioning ArrayList backup class that checks if the ArrayList already exists. Basically it's just a for-loop cycling through the list and manually adding them to the new list.

    import java.util.ArrayList;
    
    public class Snapshot {
        private ArrayList dataBackup;
    
        public Snapshot(ArrayList data)
        {
            dataBackup = new ArrayList();
            for(int i = 0; i < data.size(); i++)
            {
                dataBackup.add(data.get(i));
            }
        }
    
        public ArrayList restore()
        {
            return dataBackup;
        }
    
        public static void main(String[] args)
        {
            ArrayList list = new ArrayList();
            list.add(1);
            list.add(2);
    
            Snapshot snap = new Snapshot(list);
    
            list.set(0, 3);
            list = snap.restore();
    
            System.out.println(list); // Should output [1, 2]
    
            list.add(4);
            list = snap.restore();
    
            System.out.println(list); // Should output [1, 2]
        }
    }
    

提交回复
热议问题