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
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](https://dsd5zvtm8ll6.cloudfront.net/si.question.images/images/question_images/1605/7/8/1/8155fb6493732d011605781815257.jpg)
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.
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 the shallow clone. } data[i].getClass( ); my_class.getMethod ("clone", new Class[0]); my_clone_method.invoke (data[i], new Object[0]); =
Step by Step Solution
3.44 Rating (167 Votes )
There are 3 Steps involved in it
Here is an implementation of the bags clone method using deep cloning in Java public class ArrayBag ... View full answer
Get step-by-step solutions from verified subject matter experts
