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?

A J
  • 1,439
  • 4
  • 25
  • 42
Schupp
  • 25
  • 5
  • 1
    Because `matrix` is an array of references to `int[]` arrays, essentially – juanpa.arrivillaga May 24 '18 at 20:55
  • *Now i use systemcopy to Fix this, but why?* Because `int[]` **isn't** a primitive type. – Elliott Frisch May 24 '18 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? – ernest_k May 24 '18 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: https://stackoverflow.com/q/40480 . FYI, you can also use `matrix[0].clone()` to create a copy. – Jorn Vernee May 24 '18 at 20:58

2 Answers2

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).

morenoadan22
  • 234
  • 1
  • 9
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.

John Luo
  • 11
  • 2