I tried to make an independent copy of an array but couldnt get one. see i cannot copy it integer by integer using a for loop because of efficiency reasons. Is there any oth
Arrays.copyOf() creates a new copy of an existing array (optionally with a different length).
You can use System.arraycopy, but I doubt it will be much more efficient. The memory has to be copied anyways, so the only optimization possible is to copy bigger chunks of memory at once. But the size of a memory chunk copied at once is strongly limited by the processor/system-architecture.
Check out System.arraycopy(). It can copy arrays of any type and is a preffered(and optimized) way to copy arrays.
Try using clone ()
method for this purpose. As I remember this is the only case where Josh Bloch in Effective Java recommended to use cloning.
int[] temp = arr.clone ();
But arrayCopy is much faster. Sample performance test on array of 3,000,000 elements:
System.arrayCopy time: 8ms
arr.clone() time: 29ms
Arrays.copyOf() time: 49ms
simple for-loop time: 75ms
Look at System.arraycopy() method. Like,
int[] b = new int[a.length];
System.arraycopy(a, 0, b, 0, a.length);