You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中数组是否按引用传递给方法?为何示例代码未输出反转结果?

Does Java pass arrays by reference? Why doesn't my reverse code work?

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:

  1. In main, oldList is a reference variable pointing to the array {1,2,3,4,5} stored in memory.
  2. When you call reverse(oldList), Java passes a copy of oldList's reference to the list parameter. Now both oldList and list point to the same original array.
  3. Inside reverse, you create newList—a brand new array in memory with reversed values.
  4. When you do list = newList, you're only updating what the local list variable points to. The original oldList in main still 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:30:44