如何在java中重新初始化int数组

时间:2009-12-04 16:02:39

标签: c# java arrays int

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数组?感谢帮助。

6 个答案:

答案 0 :(得分:4)

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

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

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

答案 1 :(得分:2)

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

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

答案 2 :(得分:1)

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

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

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

在Main内部,调用方法后,第一个元素是:888 **

问问自己,为什么在调用 Change() arr [0] 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]);
    }
}

答案 3 :(得分:0)

当数组初始值设定项存在时,您无法提供尺寸。

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

答案 4 :(得分:0)

正如您所正确指出的那样,这是 impossibile ,Java参数传递语义(C#具有这些方案的ref关键字)。

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

答案 5 :(得分:0)

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