Modify the bag from the previous exercise so that all of the add methods attempt to make

Question:

Modify the bag from the previous exercise so that all of the add methods attempt to make a clone of any item that is added to the bag. These clones are then put in the bag (rather than just putting a reference to the original item into the bag). Because you don’t know whether the type of items in the bag have a public clone method, you’ll need to attempt to clone in a manner that is similar to 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


Previous Exercise

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.

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

Step by Step Answer:

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