0

I know this question has been asked before in regards to Java, but I am currently trying out Processing and none of the solutions have worked for me. I have two arrays:

int[][] array1 = {{1,2,3},{4,5,6}};
int[][] array2 = {{7,8,9},{10,11,12}};
arrayCopy(array1,array2);
array2[0][1] = 100;
println(array1[0][1]);
//prints 100 despite never altering it

Things I have tried:

//For Loop
for(int i = 0; i < array1.length; i++){
  array2[i] = array1[i];
}

//Cloning
array2 = array1.clone();
1
  • What is the implementation of the arrayCopy method? Commented Nov 12, 2017 at 16:01

1 Answer 1

2

if you refer to the documentation for the arrayCopy function, it says

If arrayCopy is used with a two (or three or more) dimensional array, it will only copy the references at the first level, because a two dimensional array is simply an "array of arrays".

So essentially modifying any of the arrays within array2 will also modify the corresponding array within array1. However, this would not be the case had you used a single dimensional array.

if you wish to copy each array of array1 to array2 without any of the said behaviour then you'll need to create a nested for loop which iterates through each of the elements (jagged array) of array1 and copy their contents ( integers ) into another array.

example:

int[][] sequence = {{1, 2, 3}, 
                    {4, 5, 6}};
int[][] accumulator = new int[sequence.length][3];

for (int i = 0; i < sequence.length; i++) 
    for (int j = 0; j < sequence[i].length; j++) 
        accumulator[i][j] = sequence[i][j];

as a side note, avoid naming variables array1, array2 etc. this makes it very difficult to identify the purpose of a particular variable. a variable should speak out what it does or its purpose by reading it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.