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;
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.
Everything in Java is passed by value.When you pass an array to other method, actually the reference to that array is copied.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With