简体   繁体   English

传递参数中的数组对象

[英]pass an array object in a parameter

I am new to java, I would like to know, how can we pass an array object as a parameter to a method.Lets say if I have: 我是java新手,我想知道,我们如何将数组对象作为参数传递给方法。让我们说如果我有:

public void sortArray(A[7])

What should I put in between the parenthesis? 我应该在括号之间放什么? Should it be A[length of array] or what? 应该是A[length of array]还是什么?

When you pass an array as a parameter its length and what's stored in it gets passed so you don't need to specifically specify the length. 将数组作为参数传递时,其长度以及存储在其中的内容将被传递,因此您无需专门指定长度。 For implementation, see the example below: 有关实现,请参阅以下示例:

Simple example of a method that takes in an int array as a parameter: 将int数组作为参数的方法的简单示例:

public void takeArray(int[] myArray) {
    for (int i = 0; i < myArray.length; i++) { // shows that the length can be extracted from the passed in array.
        // do stuff
    }
}

You would call this method thusly: 你可以这样调用这个方法:

Say you have an array like so: 假设你有一个像这样的数组:

int[] someArray = {1, 2, 3, 4, 5};

Then you call the above method with: 然后用以下方法调用上面的方法:

takeArray(someArray);

Just pass the array to the method. 只需将数组传递给方法即可。 You no need to mention any size. 你不需要提及任何尺寸。

void sortArray(int[] array) {
  // Code
}

// To call the method and pass this array do. //调用方法并传递此数组。

int[] array = new int[10];
sortArray(array);

for example you have procedure as you said: 例如,你有如你所说的程序:

public void sortArray(typeArray[] A){
 //code
 //code
}

calling array: 调用数组:

typeArray[] A = new typeArray[N]; //N is number of array you want to create
searchArray(A); //this how I call array

You just pass the name of the array to the method. 您只需将数组的名称传递给方法。

int[] a = new int[10];

...

bar(a);

where bar is defined like: 其中bar定义如下:

void bar(int[] a)
{
    ...
}

This way you can pass an array 这样您就可以传递数组

int[] a = new int[100];
myFunction(a);

 public void myFunction(int[] a){
       for(int i =0; i< a.lenght();i++){

                System.out.println(i);

              }

       }

You can also create an anonymous array if you don't want an array to be named like: 如果您不希望将数组命名为:还可以创建匿名数组:

public void array(int arr[])
{
    // code handling arr
}

Now for the above method you can pass an array object without creating it like: 现在,对于上面的方法,您可以传递一个数组对象而不创建它:

public static void main(String[] args)
{
   array(int[] {1,2,3,4,5});
}

This is also named as an Un-Named Array or Anonymous array. 这也称为未命名数组或匿名数组。 There is no need to create an array for call by value. 无需为按值调用创建数组。 If you don't want that array inside the main() method anymore you can use an un-named array. 如果您不再需要main()方法中的该数组,则可以使用未命名的数组。 This helps in memory saving. 这有助于节省内存。 Thankyou 谢谢

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

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