This Question is Answered

15 "helpful" answers available (5 pts)
1 Replies Last post: Nov 20, 2008 10:52 AM by Christopher Barber  
Rajiv Level 7 118 posts since
Apr 3, 2008
Currently Being Moderated

Nov 20, 2008 1:58 AM

How to copy an array  into another one?

 

Hi,

 

 

I want to copy one array into another ,cloning the array will do shallow copy.but I need deep copy, ]

 

 

so that new array should not refer to sameelement of first array

 

 

def  new-array = {my-array-1.clone}

 

 

 

 

Iterating over 1st array and copying element by element into another array could be one possible solution but that seems a big overhead.

 

 

As in case of java  System.arraycopy  api is available, similar api im looking in curl.

 

 

Thanks

 

 

Rajiv

 

 

 

 

 

 

Christopher Barber BlackBelt 139 posts since
Sep 27, 2007
Currently Being Moderated
1. Nov 20, 2008 10:52 AM in response to: Rajiv
Re: How to copy an array  into another one?

In order to implement a deep clone operation, the elements themselves have to implement some sort of 'clone' method, but not all Curl objects have such a method. Java has a 'clone' method in its Object class, but Curl does not. Even so, Java's clone method throws an exception by default, so there is no guarantee that any given Java object is cloneable. Also, as far as I know, Java's arraycopy function actually does a shallow copy, not a deep copy.

 

In any case, iterating over the array and copying each element is what you need to do, and the overhead is no different than it would be for doing a deep copy in Java or any other language. So assuming your array element type 'E' implements a 'clone' method, you would write:

 


def new-array = {new {Array-of E}, efficient-size = my-array-1.size}
{for e in new-array do
   {new-array.append {e.clone}}
}

 

or you could just do an array clone, and then write over the elements:

 


def new-array = {my-array-1.clone}
{for e key i in new-array do
   set new-array+ = {e.clone}
}

 

More Like This

  • Retrieving data ...