4

I want to copy a large array of integer values say form array a to array b. I have found a couple of ways to do this, including:

int[] a = new int[]{1,2,3,4,5}; int[] b = new int[5]; System.arraycopy( a, 0, b, 0, a.length ); 

and

int[] a = new int[]{1,2,3,4,5}; int[] b = (int[])a.clone(); 

Since this is done on a mobile device i want to be able to do it most efficiently.

Please tell me the best way to do this.

3
  • arraycopy is the best option Commented Feb 6, 2013 at 7:31
  • 1
    Let's not forget Arrays.copyOf. stackoverflow.com/questions/12157300/clone-or-arrays-copyof Commented Feb 6, 2013 at 7:39
  • @jdb it's risky - it's not available in earlier Android APIs, eg. API 8. Commented Feb 6, 2013 at 7:42

5 Answers 5

9

System.arraycopy is better way.

Reason: Its implemented through native code so it's more efficient. Josh Bloch suggests (in Effective Java ) to avoid using clone() method to copy/clone an object.

Pls refer this : Effective Java: Analysis of the clone() method

Sign up to request clarification or add additional context in comments.

1 Comment

@wojci apples and oranges - this is a comparison between arraycopy() and naive copying by looping over all the elements - this is not the same thing as clone().
3

I think this is the best way to make copies of arrays

int[] b = Arrays.copyOf(a, a.length); 

1 Comment

just be aware that Arrays.copyOf() was added later to the API - it's not available in API 8 for example.
2

System.arraycopy( a, 0, b, 0, a.length ); is a nice optimized function, if you build a new object, the execution will be slower..

Comments

2

Yeah, everybody's saying that arraycopy() is better, but most of people tend to forget that Dalvik VM is not Oracle VM and the sources they link to are referring to the Oracle VM. My guess is also that arraycopy() will be faster.

However

If you really, really need for this copy to most optimized, just time both methods and see how they perform. That is always the way to go if you really want to know the real answer. Do that especially on the devices you're targeting since it may be that it behaves drastically different from one device to another.

Comments

1

System.arraycopy is native implementation and efficient than cloning. It could copy array in single memorycopy(memcpy).

Find a article on wikipedia - java cloning disadvantage and alternative

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.