2
class PassingRefByVal 
{
    static void Change(int[] pArray)
    {
        pArray[0] = 888;  // This change affects the original element.
        pArray = new int[5] {-3, -1, -2, -3, -4};   // This change is local.
        System.Console.WriteLine("Inside the method, the first element is: {0}", pArray[0]);
    }

    static void Main() 
    {
        int[] arr = {1, 4, 5};
        System.Console.WriteLine("Inside Main, before calling the method, the first element is: {0}", arr [0]);

        Change(arr);
        System.Console.WriteLine("Inside Main, after calling the method, the first element is: {0}", arr [0]);
    }
}

我必须将此 c# 程序转换为 java 语言。但是这条线让我很困惑

pArray = new int[5] {-3, -1, -2, -3, -4}; // 此更改是本地的。

如何重新初始化 java int 数组?感谢帮助。

4

6 回答 6

6
pArray = new int[] {-3, -1, -2, -3, -4};

即,无需指定初始大小 - 编译器可以计算大括号内的项目。

另外,请记住,当 java 按值传递时,您的数组不会“改变”。您必须返回新数组。

于 2009-12-04T16:06:20.817 回答
2

您不能从其他方法中“重新初始化”数组,因为 Java 是按值传递的。您可以使用 ref 关键字在 C# 中解决此问题,但这在 Java 中不可用。您将只能通过调用方法更改现有数组中的元素。

如果您只想在本地更改阵列,那么 Bozho 的解决方案将起作用。

于 2009-12-04T16:06:48.397 回答
1

这是 C# 程序打印的内容:

**在Main里面,在调用方法之前,第一个元素是:1

在方法内部,第一个元素是:-3

Main里面,调用方法后,第一个元素是:888**

问问自己,为什么arr[0]在调用Change( ) 之后在 Main()中设置为 888 ?你期待-3吗?

这是正在发生的事情。int 数组变量pArray在Change()方法中被视为局部变量。它最初设置为对传递给它的数组实例的引用。(在示例程序中,这将是Main ()中的arr)。线

**pArray = new int[5] { -3, -1, -2, -3, -4 };   // This change is local.**

导致创建一个新数组,并将 pArray 设置为对这个新数组的引用,而不是来自Main()的arr

该程序没有打印出数组长度。如果有,长度将分别为 3、5 和 3。

您可以尝试以下方法:

public class TestPassByRefByVal
{
    public static void Change(int[] pArray)
    {
        int [] lArray = { -3, -1, -2, -3, -4 };
        pArray[0] = 888;  // This change affects the original element.
        pArray = lArray;     // This change is local.
        System.out.println("Inside the method, the first element is: " + pArray[0]);
    }

    public static void main(String[]args)
    {
        int [] arr = { 1, 4, 5 };
        System.out.println("Inside Main, before Change(), arr[0]: " + arr[0]);

        Change(arr);
        System.out.println("Inside Main,  after Change(), arr[0]: " + arr[0]);
    }
}
于 2009-12-04T17:07:56.260 回答
0

当存在数组初始化器时,您无法提供维度,即

 pArray = new int[5] {-3, -1, -2, -3, -4};
于 2009-12-04T16:07:11.740 回答
0

正如您正确指出的那样,这对于 Java 参数传递语义是不可能的(C# 具有这些场景的 ref 关键字)。

由于 Java 数组的大小是不可变的,因此您只能更改值,而不是数组的长度(它不能增长也不能缩小)。

于 2009-12-04T16:14:40.970 回答
0

如果要在 java 中更改大小,可能需要使用 Vector 或 ArrayList

于 2009-12-04T17:15:56.480 回答