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.len gth];
//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
//Clone the Original array
Object[] SortedArray = new Object[arry_of_objects.len
//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
Test[] SortedArray = new Test[arry_of_objects.lengt
//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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.lengt
//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()