Link to home
Start Free TrialLog in
Avatar of walker222
walker222

asked on

Object cloning

I am trying to write a class which takes an array of objects(can be any type of object, even user defined classes) and returns a sorted copy of the array.  In my sort function, I am trying to clone the Object array using the lines of code:

//Clone the Original array
Object[] SortedArray = new Object[arry_of_objects.length];


//Clone the individual objects in the array into
//the new array  
for (int i = 0; i < array_of_objects.length; i++)
    SortedArray [i] = (Object) arry_of_objects[i].clone();
     

   But it will not let me do this since the clone() method is protected.  So...How can I go about cloning the inidivual objects into a new array?  Thanks
Avatar of allahabad
allahabad

The class Object does not itself implement the interface Cloneable, so calling the clone method on an object whose class is Object will result in throwing an exception at run time.

Create a class and implement Cloneable interface.
for ex.
public class Test implements  Cloneable{


    protected Object clone() {
       super.clone();
    }
}

Then your code :

Object[] SortedArray = new Test[arry_of_objects.length];


//Clone the individual objects in the array into
//the new array  
for (int i = 0; i < array_of_objects.length; i++)
   SortedArray [i] = (Test) arry_of_objects[i].clone();


Test[] SortedArray = new Test[arry_of_objects.length];


//Clone the individual objects in the array into
//the new array  
for (int i = 0; i < array_of_objects.length; i++)
  SortedArray [i] = arry_of_objects[i].clone();

ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial