0

why is the array "matrix[0]" sorted too, Systemcopy required?

int[] check = matrix[0];

Arrays.sort(check);

Now I use Systemcopy to Fix this, but why?

4
  • 1
    Because matrix is an array of references to int[] arrays, essentially Commented May 24, 2018 at 20:55
  • Now i use systemcopy to Fix this, but why? Because int[] isn't a primitive type. Commented May 24, 2018 at 20:55
  • 1
    Your question doesn't include enough information. We shouldn't suppose that matrix is 2D array. Also arrays.sorts doesn't really point to something everyone knows. Can you please edit the question? Commented May 24, 2018 at 20:56
  • int[] check = matrix[0] does not copy the array matrix[0], it just copies the reference to the array (i.e. it's a shallow copy). See also: stackoverflow.com/q/40480 . FYI, you can also use matrix[0].clone() to create a copy. Commented May 24, 2018 at 20:58

2 Answers 2

1

This line: int[] check = matrix[0] assigns a reference of the matrix[0] to check. Which means that whatever operation you do on check will be reflected in the matrix as well. Though the references are not the same, the memory locations are, unless you create a copy (like you mentioned).

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

Comments

1

When you do int[] check = matrix[0], check is now referencing matrix[0]. To make them two different arrays you need to make a deep copy.

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.