13

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; 
2
  • 2
    What "efficiency reasons"? Did you actually test that this piece of code is a problem? Or are you just guessing? Commented Mar 3, 2010 at 13:30
  • really strange efficiency reasons... Commented Mar 3, 2010 at 13:35

5 Answers 5

21

Look at System.arraycopy() method. Like,

int[] b = new int[a.length]; System.arraycopy(a, 0, b, 0, a.length); 
Sign up to request clarification or add additional context in comments.

Comments

14

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

3 Comments

Note that this method is new in 1.6 and arguably easier to use than System.arraycopy()
@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).
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
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 

3 Comments

Nice stats, but it begs the question why he should "try using clone()"
because I first wrote about clone () and then made the test for the sake of interest :)
I can't reproduce the results, see my micro-benchmark which shows that the first 3 methods are equivalent. So I would favour the Arrays.copyOf which was purposedly built for that task.
4

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

Comments

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.

1 Comment

Especially for big arrays, that method can be quite a bit faster than a simple for-loop implementation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.