-
December 5th, 2011, 09:40 PM
#1
Array Copy
Hi all,
This may be a stupid question, but how do you copy the content of one array to another.
I tried many different ways but it keep give the location of the pointer in memory rather than the right data.
Here is what I tried:
Code:
static double[] cloneArray(double original[], int n) {
double[] temp = new double[n];
for (int i = 0; i < n; i++) {
temp[i] = original[i];
}
return temp;
}
Thanks in advance.
-
December 6th, 2011, 04:06 AM
#2
Re: Array Copy
Your code is correct although the easiest way of doing this is to use System.arraycopy(..).
but it keep give the location of the pointer in memory rather than the right data.
How are you looking at the array contents?
-
December 6th, 2011, 10:16 AM
#3
Re: Array Copy
Essentially I did use System.arraycopy but I realized that I am printing the array wrong.
I should use:
Code:
private static void print(double[] lines) {
for(int i = 0; i < lines.length; i++)
System.out.println(lines[i]);
}
Instead of just
Code:
System.out.println(arryName]);
Thanks.
-
December 6th, 2011, 11:20 AM
#4
Re: Array Copy
Or you could print it like this:
Code:
System.out.println(Arrays.toString(lines));
Arrays is a class in the java.util package that has a lot of useful methods for sorting, searching, filling, copying, printing arrays of any primitive or object type.
-
December 6th, 2011, 05:53 PM
#5
Re: Array Copy
Thanks. I'll look more into the array class and find out what else is possible with it.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|