【问题标题】:pass array to method Java将数组传递给 Java 方法
【发布时间】:2009-10-23 00:15:58
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: java arrays


    【解决方案1】:

    你这样做:

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

    只需将其作为任何其他变量传递即可。
    在 Java 中,数组是通过引用传递的。

    【讨论】:

    • so...如果我在方法中更改数组(作为参数传入),我是否会更改调用者中原始数组中的值?
    • @Remian8985 如果数组是全局声明的,或者您通过其类(例如 someClass.array)访问它,那么可以。
    • 是的,数组在 Java 中被实现为对象,因此只需将数组的引用传递给您要调用的方法。
    【解决方案2】:

    只需从原始代码中删除括号。

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

    就是这样。

    【讨论】:

    • 嘿,我想我们以前都做过。我想知道的是为什么我们仍然必须明确地初始化我们的对象。有没有我们想要一个类型化的空指针的情况?即使是这样,这绝对是一个例外而不是常态。
    【解决方案3】:

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

    PrintA(arrayw);
    

    编辑:

    稍微详细一点。如果您要做的是创建一个数组的副本,则必须将数组传递给该方法,然后在那里手动创建一个副本(不确定 Java 是否有类似Array.CopyOf() 的东西)。否则,您将传递数组的 REFERENCE,因此如果您更改其中元素的任何值,其他方法也会更改。

    【讨论】:

      【解决方案4】:

      要点

      • 你必须使用 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

      【讨论】:

        【解决方案5】:

        数组有一个很重要的点,在 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
            }
        }
        

        【讨论】:

          【解决方案6】:

          您的语法错误。只需传入数组的名称。顺便说一句 - 阅读一些常见的格式化内容也是个好主意,例如在 Java 方法中应该以小写字母开头(这不是错误,而是约定)

          【讨论】:

            【解决方案7】:

            如果你太懒了 ;) 来声明变量。

            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));
            

            【讨论】:

              【解决方案8】:
              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();
                  }
              }
              

              【讨论】:

                【解决方案9】:
                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
                }
                

                【讨论】:

                  【解决方案10】:

                  这样我们可以将一个数组传递给一个函数,这里这个打印函数会打印数组的内容。

                  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 年提出的问题?
                  猜你喜欢
                  • 2012-11-13
                  • 1970-01-01
                  • 2013-12-18
                  • 1970-01-01
                  • 2021-06-04
                  • 2013-10-04
                  • 2015-02-16
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多