将数组传递给Java方法

37

如何将整个数组传递给一个方法?

private void PassArray() {
    String[] arrayw = new String[4];
    //populate array
    PrintA(arrayw[]);
}

private void PrintA(String[] a) {
    //do whatever with array here
}

我该如何正确地做到这一点?

10个回答

63

你可以这样做:

private void PassArray() {
    String[] arrayw = new String[4]; //populate array
    PrintA(arrayw);
}

private void PrintA(String[] a) {
    //do whatever with array here
}

像处理其他变量一样传递它。
在Java中,数组是按引用传递的。


3
如果我在一个方法中改变数组(作为参数传递),那么我会改变调用者原始数组中的值吗? - Noobification
1
如果数组是全局声明的,或者通过其类(例如,someClass.array)访问它,则是的。 - TheEyesHaveIt
是的,在Java中,数组被实现为对象,因此只需要将数组的引用传递给您想要调用的方法即可。 - AnkitSablok

14

只需从您的原始代码中删除括号即可。

PrintA(arryw);

private void PassArray(){
    String[] arrayw = new String[4];
    //populate array
    PrintA(arrayw);
}
private void PrintA(String[] a){
    //do whatever with array here
}

就是这样了。


嘿,我想我们都曾经这样做过。我想知道的是为什么我们仍然需要显式地初始化对象。是否存在任何情况下我们想要一个类型化的空指针?即使有这种情况,它肯定是个例外而不是常态。 - Daniel T.

9

数组变量只是一个指针,所以你可以像这样传递它:

PrintA(arrayw);

编辑:

稍微解释一下。如果你想要创建一个数组的副本,你需要将数组传递到方法中,然后在方法内部手动创建一个副本(不确定Java是否有类似Array.CopyOf()的方法)。否则,你将传递数组的引用,如果你改变其中任何元素的值,其他方法也会受到影响。


6
数组有一个重要的点在Java课程中通常未被教授或忽略。当数组传递给函数时,会创建另一个指向同一数组的指针(从未传递相同的指针)。您可以使用两个指针操作数组,但是一旦将第二个指针分配给调用方法中的新数组并通过void返回到调用函数,则原始指针仍然保持不变。您可以直接在此处运行代码:https://www.compilejava.net/
import java.util.Arrays;

public class HelloWorld
{
    public static void main(String[] args)
    {
        int Main_Array[] = {20,19,18,4,16,15,14,4,12,11,9};
        Demo1.Demo1(Main_Array);
        // THE POINTER Main_Array IS NOT PASSED TO Demo1
        // A DIFFERENT POINTER TO THE SAME LOCATION OF Main_Array IS PASSED TO Demo1

        System.out.println("Main_Array = "+Arrays.toString(Main_Array));
        // outputs : Main_Array = [20, 19, 18, 4, 16, 15, 14, 4, 12, 11, 9]
        // Since Main_Array points to the original location,
        // I cannot access the results of Demo1 , Demo2 when they are void.
        // I can use array clone method in Demo1 to get the required result,
        // but it would be faster if Demo1 returned the result to main
    }
}

public class Demo1
{
    public static void Demo1(int A[])
    {
        int B[] = new int[A.length];
        System.out.println("B = "+Arrays.toString(B)); // output : B = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        Demo2.Demo2(A,B);
        System.out.println("B = "+Arrays.toString(B)); // output : B = [9999, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        System.out.println("A = "+Arrays.toString(A)); // output : A = [20, 19, 18, 4, 16, 15, 14, 4, 12, 11, 9]

        A = B;
        // A was pointing to location of Main_Array, now it points to location of B
        // Main_Array pointer still keeps pointing to the original location in void main

        System.out.println("A = "+Arrays.toString(A)); // output : A = [9999, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        // Hence to access this result from main, I have to return it to main
    }
}
public class Demo2
{
    public static void Demo2(int AAA[],int BBB[])
    {
        BBB[0] = 9999;
        // BBB points to the same location as B in Demo1, so whatever I do
        // with BBB, I am manipulating the location. Since B points to the
        // same location, I can access the results from B
    }
}

5

重要注意事项

  • 您必须使用java.util包
  • 数组可以通过引用传递

在方法调用语句中

  • 不要使用任何对象来传递数组
  • 仅使用数组的名称,不要使用数据类型或数组括号[]

示例程序

import java.util.*;

class atg {
  void a() {
    int b[]={1,2,3,4,5,6,7};
    c(b);
  }

  void c(int b[]) {
    int e=b.length;
    for(int f=0;f<e;f++) {
      System.out.print(b[f]+" ");//Single Space
    }
  }

  public static void main(String args[]) {
    atg ob=new atg();
    ob.a();
  }
}

输出示例程序

1 2 3 4 5 6 7


1

如果你太懒了,不想声明变量。

import static org.junit.Assert.assertEquals
public class BinarySearch 
{

    public static void main(String[] args) 
    {
        search(new int[] {-1,0,3,5,9,12}, 9); //creating and passing array
    }
    public static int search(int[] nums, int target) 
    {
        //write some code
        return -1;
    }
}

这对于像下面这样的单元测试非常有用

assertEquals(4,search(new int[] {-1,0,3,5,9,12}, 9));
assertEquals(-1,search(new int[]{-1,0,3,5,9,12}, 2));

1

你的语法有误。只需传递数组的名称即可。顺便说一句 - 最好也阅读一些常见的格式化内容,例如在Java中方法应以小写字母开头(这不是错误,而是约定俗成)


0
public static void main(String[] args) {

    int[] A=new int[size];
      //code for take input in array
      int[] C=sorting(A); //pass array via method
      //and then print array

    }
public static int[] sorting(int[] a) {
     //code for work with array 
     return a; //retuen array
}

0
class test
{
    void passArr()
    {
        int arr1[]={1,2,3,4,5,6,7,8,9};
        printArr(arr1);
    }

    void printArr(int[] arr2)
    {
        for(int i=0;i<arr2.length;i++)
        {
            System.out.println(arr2[i]+"  ");
        }
    }

    public static void main(String[] args)
    {
        test ob=new test();
        ob.passArr();
    }
}

0
通过这种方式,我们可以将一个数组传递给一个函数,在这里,这个打印函数将打印出数组的内容。
public class PassArrayToFunc {

    public static void print(char [] arr) {
        for(int i = 0 ; i<arr.length;i++) {
            System.out.println(arr[i]);
        }
    }

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        char [] array = scan.next().toCharArray();
        print(array);
        scan.close();
    }

}

认真的吗?回答一个2009年提出的问题? - u32i64

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接