简体   繁体   English

在Java中将数组作为参数传递

[英]passing array as argument in java

i wants to pass array as arguments to sub class from main . 我想将数组作为参数传递给main的子类。 but looks like its not initialized.Please have a look on below and advice where i am wrong. 但看起来好像它没有初始化。请在下面看看并建议我错了。 Thanks in Advance 提前致谢

    class arraymain{
    public static void main(String[] arg){

        Array obj=new Array();
        obj.passArray(new int[]{1,2,3,4,5},4);
    }
    }
 class Array{
 void passArray(int[] values,int size){

   values=new int[size];
        for (int num=0;num<values.length;num++){
            System.out.println(values[num]);

        }
    }

}
OUPTPUT:
0
0
0
0
values=new int[size];

You are initializing a new array, overwriting the passed parameter. 您正在初始化一个新数组,覆盖传递的参数。

When creating a new array this way, all values are initialized with their default values, for int this happens to be 0. 当以这种方式创建新数组时,所有值都将使用其默认值进行初始化,因为int恰好是0。

Simply remove this line, and the code should work as intended. 只需删除这一行,代码即可按预期工作。

And, as a comment points out, this makes the parameter size unused. 并且,正如注释所指出的,这使参数size未使用。 The length of the array is derived directly from the array, as you already do in your code. 数组的长度直接从数组派生,就像您在代码中所做的一样。

You need to remove values=new int[size]; 您需要删除values=new int[size]; from your Array class. 从您的Array类。

You are getting values as parameter, and then you are doing this values=new int[size]; 您将获取values作为参数,然后执行此values=new int[size]; , which creates a new array, and this new array has no values (default values 0). ,这将创建一个新数组,并且此新数组没有值(默认值为0)。

The problem is the line 问题是线

values=new int[size]

You are creating a new array, and thereby you are hiding the one with non-0 values. 您正在创建一个新的数组,从而隐藏了一个非零值的数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM