12

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 other way? This was my code:

int[] temp = new int[arr.length]; 
temp = arr; 
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
higherDefender
  • 1,551
  • 6
  • 23
  • 35

5 Answers5

20

Look at System.arraycopy() method. Like,

int[] b = new int[a.length];
System.arraycopy(a, 0, b, 0, a.length);
Chandra Sekar
  • 10,683
  • 3
  • 39
  • 54
14

Arrays.copyOf() creates a new copy of an existing array (optionally with a different length).

matt b
  • 138,234
  • 66
  • 282
  • 345
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • 1
    Note that this method is new in 1.6 and arguably easier to use than System.arraycopy() – matt b Mar 03 '10 at 14:34
  • @matt: I no longer mention "new in Java 6", because Java 6 is old enough already (December 2006 is already some time in the past). – Joachim Sauer Mar 03 '10 at 14:36
  • I didn't mean that as a reason to not use it - just a heads up for anyone who isn't familiar with it because they aren't using 1.6 – matt b Mar 03 '10 at 15:33
6

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
Roman
  • 64,384
  • 92
  • 238
  • 332
  • Nice stats, but it begs the question why he should "try using clone()" – Draemon Mar 03 '10 at 14:00
  • 1
    because I first wrote about clone () and then made the test for the sake of interest :) – Roman Mar 03 '10 at 14:19
  • I can't reproduce the results, see [my micro-benchmark](http://stackoverflow.com/a/12157504/829571) which shows that the first 3 methods are equivalent. So I would favour the `Arrays.copyOf` which was purposedly built for that task. – assylias Aug 28 '12 at 10:45
4

Check out System.arraycopy(). It can copy arrays of any type and is a preffered(and optimized) way to copy arrays.

pajton
  • 15,828
  • 8
  • 54
  • 65
1

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.

Mnementh
  • 50,487
  • 48
  • 148
  • 202