4

Possible Duplicate:
Make copy of array Java

I'm a beginner at Java and I need to copy the contents of one array into another variable. However, Java always passes the array by reference instead of by value.

Here's what I mean if that was confusing:

int test[]={1,2,3,4};
int test2[];
test2=test;
test2[2]=8;
for(int i=0;i<test2.length;i++)
    System.out.print(test[i]); // Prints 1284 instead of 1234

In this example, I don't want the value of test to change. Is this possible without using any of the more advanced features of Java such as ArrayList and Vectors?

Edit: I tried System.ArrayCopy and test.clone(), but they still don't seem to work. Here's my actual code:

temp_image=image.clone();
for(int a=0;a<image.length;a++)
    for(int b=0;b<image[0].length;b++)
        image[a][b]=temp_image[image.length-1-a][b];

Basically I'm trying to flip the "image" upside down. Is there an error somewhere in the code?

Community
  • 1
  • 1
Leo Jiang
  • 24,497
  • 49
  • 154
  • 284
  • System.arraycopy: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html – Luiggi Mendoza Apr 13 '12 at 02:34
  • @LuiggiMendoza you might want to start using more recent JavaDocs; [Java 1.4 is 3 versions (10 years) behind](http://en.wikipedia.org/wiki/Java_version_history). – Matt Ball Apr 13 '12 at 02:37
  • Surely there are like 2000 exact duplicates of this? –  Apr 13 '12 at 02:43
  • 1
    I'm pretty sure there are over 9000. – Kaleb Brasee Apr 13 '12 at 02:45
  • @MДΓΓБДLL well, if you check the link in your comment, it refers to `System.arraycopy` too! – Luiggi Mendoza Apr 13 '12 at 02:50
  • @LuiggiMendoza all I meant was that you should link to [non-obsolete JavaDocs](http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#arraycopy%28java.lang.Object,%20int,%20java.lang.Object,%20int,%20int%29). – Matt Ball Apr 13 '12 at 03:49

3 Answers3

5

You need to clone your array.

test2=test.clone();
kba
  • 19,333
  • 5
  • 62
  • 89
2

Starting in Java 6 you can use Arrays.copyOf:

test2 = Arrays.copyOf(test, test.length);

For what you're looking to do, test.clone() is fine. But if you wanted to do a resize, copyOf allows you to do that. I think in terms of performance it

System.arraycopy would give even more options if you needed them.

Kaleb Brasee
  • 51,193
  • 8
  • 108
  • 113
0

Because test and test2 are both pointers to the same array, you are changing the value of both test and test2 with your statement test2[2]=8

A solution would be to copy the contents of test into test 2 and change the value at the specific index of test2.

    for (int i=0,i<test.length,i++)
        test2[i]=test[i]
    //Now both arrays have the same values

    test2[2]=8

    for (int j=0,j<test.length,j++)
        System.out.print(test[i])
        System.out.println()
        System.out.print(test2[i])

Will output

    1 2 3 4
    1 2 8 4
ironcyclone
  • 199
  • 1
  • 6