为何Arrays.sort会修改原数组?matrix[0]连带排序与SystemCopy作用
Great questions—they cut straight to the heart of how Java handles arrays and memory, which is a super common point of confusion for developers. Let's break them down one by one.
1. Why does Arrays.sort() modify the original array?
The short answer: Arrays.sort() is built to perform an in-place sort.
In-place sorting algorithms work directly on the input data structure instead of creating a separate copy to sort. This is intentional—it saves memory by avoiding the need to allocate space for an entirely new array just to rearrange elements. The Arrays.sort() implementation uses optimized in-place logic (like Dual-Pivot QuickSort for primitive arrays, or TimSort for object arrays) that shuffles elements directly within the original array's memory space.
If you wanted to keep the original array untouched, you'd first make a copy of it, then sort that copy instead.
2. Why does sorting check affect matrix[0], and how does System.arraycopy() fix this?
This all comes down to how Java handles array references—let's walk through it:
When you write int[] check = matrix[0];, you aren't creating a new array with the same elements as matrix[0]. Instead, you're making the check variable point to the exact same array object that matrix[0] references. Think of it like both variables hold a "pointer" to the same spot in memory where the array lives.
So when you call Arrays.sort(check);, you're sorting that single shared array. That's why matrix[0] also appears sorted—because it's the very same array!
System.arraycopy() fixes this by creating a full copy of the array elements into a brand-new array object. When you use it, you're allocating fresh memory for a new array, copying every element from matrix[0] into this new space, then making check point to this new array. Now, when you sort check, you're only modifying this separate array—matrix[0] stays untouched because it still points to the original, unmodified array in memory.
Here's a quick example of how to implement this fix:
int[] check = new int[matrix[0].length]; System.arraycopy(matrix[0], 0, check, 0, matrix[0].length); Arrays.sort(check);
内容的提问来源于stack exchange,提问作者Schupp

