In such situations, there are three general solutions:
(1) If you know that individual elements have clone () methods that work the way you intend, create a new array and fill it with clone () of each corresponding element. Generally, the “core” objects from the JDK, such as strings, numbers, etc., must be accurate. The disadvantage of clone () is that it is a little "empty gun": you do not know a priori exactly how deep the "clone" will be if the method was overridden for a particular class and which links could potentially be reused or not. It also has a special "strong" danger that subclasses of cloned objects that rely on logic in their constructor cannot work. But, as I say, simple JDK objects should be fine.
(2) Serialize an ObjectOutputStream list wrapped in a ByteArrayOutputStream. Then take the resulting byte array and wrap ByteArrayInputStream and ObjectInputStream around it and read a new, deep copy of the list from it.
(3) In an ideal world, create a new list by filling it with explicitly created “copies” of the objects in question. If this is not too cumbersome for the code, this is the ideal solution because you “know what is actually happening”: there will be no hidden surprises regarding objects that would be accidentally redirected and not re-created, for example, the clone () method didn't work as you expected.
Since you have a simple container object (a list of arrays) whose structure you can easily recreate, then (2) may be redundant. This can be convenient for re-creating more complex structures.
Re (1), you should be especially suspicious of cloning objects from third-party libraries , where objects have not been specifically designed with the clone () function in mind. The problem is that it is easy for people to subclass the JDK class (cloneable) or the token clone () method without thinking about it in detail - in my experience, clone () has some subtleties that many developers do not (for example, that the constructor does not call new object call), which can lead to unforeseen problems. Therefore, if you cannot see reliable source code to be sure that clone () will be safe, I would avoid this.
Neil coffey
source share