代码之家  ›  专栏  ›  技术社区  ›  Batakj

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

  •  1
  • Batakj  · 技术社区  · 16 年前
    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//此更改是本地更改。

    如何重新初始化Javaint数组?谢谢你的帮助。

    6 回复  |  直到 16 年前
        1
  •  4
  •   Bozho    16 年前
    pArray = new int[] {-3, -1, -2, -3, -4};
    

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

    此外,请记住,当Java通过值传递时,数组不会“更改”。必须返回新数组。

        2
  •  2
  •   Taylor Leese    16 年前

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

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

        3
  •  1
  •   Jay Elston    16 年前

    以下是C程序打印的内容:

    **在main中,在调用方法之前,第一个元素是:1

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

    在main中,调用方法后,第一个元素是:888**

    问问自己,为什么 arr[0] 设置为888英寸 主体() 在接到电话后 变换() ?你想-3吗?

    这是发生的事情。int数组变量 帕雷 变换() 方法。它最初被设置为对传递给它的数组实例的引用。(在示例程序中,这将是 ARR 在里面 主体() )线

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

    导致创建新数组,并且parray被设置为对此新数组的引用,而不是 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]);
        }
    }
    
        4
  •  0
  •   Gordon    16 年前

    当存在数组初始化器时,不能提供维度,即

     pArray = new int[5] {-3, -1, -2, -3, -4};
    
        5
  •  0
  •   dfa    16 年前

    正如您正确指出的,这是 不可能的 通过Java参数传递语义(C语言具有这些场景的REF关键字)。

    因为Java数组是 大小不可变 您只能更改值,而不能更改数组的长度(它不能增长或收缩)。

        6
  •  0
  •   Steve Zhang    16 年前

    如果要更改Java中的大小,可能需要使用vector或ARARYLIST