Java中数组是否按引用传递给方法?为何示例代码未输出反转结果?
First, let's clear up the core confusion: Java uses pass-by-value for all parameter passing. For reference types (like arrays, objects), the "value" being passed is a copy of the reference that points to the actual object in memory. This often feels like pass-by-reference, but it's not—and that's exactly why your code isn't behaving as expected.
Let's break down your code step by step
Your reverse method creates a new reversed array and assigns it to the list parameter, but this doesn't change the original array in main. Here's why:
- In
main,oldListis a reference variable pointing to the array{1,2,3,4,5}stored in memory. - When you call
reverse(oldList), Java passes a copy ofoldList's reference to thelistparameter. Now botholdListandlistpoint to the same original array. - Inside
reverse, you createnewList—a brand new array in memory with reversed values. - When you do
list = newList, you're only updating what the locallistvariable points to. The originaloldListinmainstill references the original array, because you never modified that original reference—you only changed the copy.
Since the original array's elements were never altered, your output remains 1 2 3 4 5.
How to fix the reverse method to modify the original array
Instead of creating a new array and reassigning the parameter, modify the elements of the existing array that list references. Here's a corrected version:
public static void reverse(int[] list) { // Swap elements from start and end moving toward the center for (int i = 0; i < list.length / 2; i++) { int temp = list[i]; list[i] = list[list.length - 1 - i]; list[list.length - 1 - i] = temp; } }
This approach directly updates the elements of the array that both list and oldList point to. When the method finishes, oldList in main will still reference the same array—but its elements are now reversed, so your output will be 5 4 3 2 1.
Key takeaway
- Java is always pass-by-value. For reference types, the value passed is a copy of the reference to the object.
- Assigning a new object to a parameter variable never affects the original reference in the caller.
- To modify the original object, you need to change its internal state (like array elements) rather than reassigning the parameter.
内容的提问来源于stack exchange,提问作者CHUCHU YAO

