How to backup ArrayList in Java?

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

    I'm assuming data is the name of the ArrayList you wanted to backup. If so, you should know that clone is not deep - it only creates a copy of the object on which it is invoked, which in this case is the list. If it were a deep clone, it would fill the new list with clones of the objects in it.

    Since it's not deep, if you change the objects the list contains, then the backup list will show those changes as well, since it's containing the same objects. The only time you'll not see changes in the backup after changing the "current" list is when you add or remove objects from the current list.

    Some classes may override clone to be deep, but not all. In general, it's not something you can rely on. When creating a backup copy of Java collections, remember to either clone the contained objects as well, or deal only with collections of immutable objects.

提交回复
热议问题