Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copying array by value in java

Tags:

java

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; 
like image 474
higherDefender Avatar asked Mar 03 '10 13:03

higherDefender


People also ask

How do I copy a 2d array in Java?

1. Using clone() method. A simple solution is to use the clone() method to clone a 2-dimensional array in Java. The following solution uses a for loop to iterate over each row of the original array and then calls the clone() method to copy each row.

Are arrays copied by reference in Java?

Everything in Java is passed by value.When you pass an array to other method, actually the reference to that array is copied.


1 Answers

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
like image 173
Roman Avatar answered Sep 17 '22 15:09

Roman