News:

ASSUMING DIRECT CONTROL.

Main Menu

Java coding help!

Started by Zovistograt, January 16, 2008, 04:23:01 PM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Zovistograt

I really hope SOMEONE here knows Java.  I'd like to know how to duplicate an array into another array without the second array being subject to alterations to the first array.  As it stands, when an index of the first array is changed, at same index of the second array is also changed making this entire thing pointless.  How do I fix this?
"I lovat a gabber.  I could listen to maure and moravar again.  Regn onder river.  Flies do your float.  Thick is the life for mere." - James Joyce (Finnegans Wake, page 213)

Rius

You'll have to copy the first array into another array; since arrays are Objects, when you try to use initializing expressions using another array you won't copy it, you'll just have another reference to the same array.

One array, two references:

int[] a = new int{3. 6. 9};
int[] b = a;
b[1] = 2;

System.out.println(a + "\n" + b);


Yields:
{3, 2, 9}
{3, 2, 9}


The only way I'm aware of fixing this is copying the old array into a new array. There may be another way using some weird method, but it is unknown to me. A loop can easily copy the array.

Two arrays, two references:

int[] a = new int{3. 6. 9};
int[] b = new int[a.length];

for (int i = 0; i < a.length; i++)
      b[i] = a[i];

b[1] = 2;

System.out.println(a + "\n" + b);


Yields:
{3, 6, 9}
{3, 2, 9}

Zovistograt

Thanks Ninning, that actually helped a lot!  I can't believe I forgot about the references anomaly D:

Now to fix that other bug...whoo
"I lovat a gabber.  I could listen to maure and moravar again.  Regn onder river.  Flies do your float.  Thick is the life for mere." - James Joyce (Finnegans Wake, page 213)