如何在Java中将数组传递给方法?

您可以像普通变量一样将数组传递给方法。当我们将数组作为参数传递给方法时,实际上是将数组在内存中的地址传递(引用)。因此,方法中对此数组的任何更改都会影响该数组。

假设我们有两种方法min() max()接受一个数组,并且这些方法分别计算给定数组的最小值和最大值:

示例

import java.util.Scanner;

public class ArraysToMethod {
   public int max(int [] array) {
      int max = 0;

      for(int i=0; i<array.length; i++ ) {
         if(array[i]>max) {
            max = array[i];
         }
      }
      return max;
   }

   public int min(int [] array) {
      int min = array[0];
   
      for(int i = 0; i<array.length; i++ ) {
         if(array[i]<min) {
            min = array[i];
         }
      }
      return min;
   }

   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the size of the array that is to be created::");
      int size = sc.nextInt();
      int[] myArray = new int[size];
      System.out.println("Enter the elements of the array ::");

      for(int i=0; i<size; i++) {
         myArray[i] = sc.nextInt();
      }
      ArraysToMethod m = new ArraysToMethod();
      System.out.println("Maximum value in the array is::"+m.max(myArray));
      System.out.println("Minimum value in the array is::"+m.min(myArray));
   }
}

输出结果

Enter the size of the array that is to be created ::
5
Enter the elements of the array ::
45
12
48
53
55
Maximum value in the array is ::55
Minimum value in the array is ::12