如何在java中重新初始化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语言。但这条线让我困惑如何在java中重新初始化int数组

pArray = new int [5] {-3,-1,-2,-3,-4}; //这个改变是本地的。我如何重新初始化java int数组?感谢帮助。

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

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

另外,请记住,随着java传递值,你的数组将不会'改变'。你必须返回新的数组。

+0

Java是按值传递。这个方法返回时不会反映出来。 – 2009-12-04 16:08:59

+0

它的工作原理。谢谢bonzo。 – Shashi 2009-12-04 16:09:43

+0

你是对的,但这是答案的另一部分。 – Bozho 2009-12-04 16:10:30

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

如果您只希望在本地更改数组,那么Bozho的解决方案将起作用。

当阵列initalizer存在即

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

为你正确地指出,这是impossibile与传递语义的Java参数(C#有这些情景裁判关键字)时,无法提供维度。

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

+0

由于该行不会改变数组,因此会错过这一点,它会分配一个新数组。 – Svante 2009-12-04 16:24:43

这里是C#的程序打印:

**内部主,调用该方法之前,所述第一元件是:1

里面的方法中,第一元件被:-3

内部主,调用该方法后,所述第一元件是:888 **

问自己,为什么ARR [0]组888在主()的CA之后ll到更改()?你期待-3?

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

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

导致创建一个新的数组,并且粒子阵列被设置为这个新的数组代替ARR的Main()的参考。

程序没有打印数组长度。如果有的话,长度分别为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]); 
    } 
} 

如果你想改变Java中的大小,您可能需要使用Vector或ArrayList中