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.

FIGURE 5.10 Setting answer.data[i] Equal to a Deep Clone of data[i] java.lang.Class my_class; java.lang.reflect.Method my_clone_method%; try { // Try to set answer.data[i] equal to a clone made by data[i].clone: my_class my_clone_method answer.data[i] } catch (Exception e) { // The clone method for data[i] wasn't available, so we have to accept

Fantastic news! We've Found the answer you've been seeking!

Step by Step Answer:

Related Book For  book-img-for-question
Question Posted: