Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 233
  • Last Modified:

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
0
walker222
Asked:
walker222
  • 2
1 Solution
 
allahabadCommented:
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();

0
 
allahabadCommented:

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();

0
 
objectsCommented:
Just try:

Object[] SortedArray = (Object[]) arry_of_objects.clone();

You'll need to ensude that all the objects in your array are cloneable.



0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now