The bags clone method creates a copy of an ArrayBag. As with other clone methods, adding or
Question:
The bag’s clone method creates a copy of an ArrayBag. As with other clone methods, adding or removing elements from the original bag will not affect the copy, nor vice versa. However, these elements are now references to objects; both the original and the copy contain references to the same underlying objects. Changing these underlying objects can affect both the original and the copy.
An alternative cloning method, called deep cloning, can avoid the problem. A deep cloning method has one extra step: Each reference to an object in the bag’s array is examined to see whether that object itself can be cloned. If so, then the object is cloned, and the new bag is given a reference to the clone of the object rather than a reference to the same object that the original bag contains. Rewrite the bag’s clone method to perform a deep cloning.
Each element in the bag’s array, such as data[i], is a Java object, and unfortunately you cannot call data[i].clone( ) directly to make a copy (since the clone method is not public for the Object class). The solution to this problem uses two classes, java.lang.Class and java.lang.reflect. Method, as shown in Figure 5.10.
Step by Step Answer: