如何在 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

更新日期: 02-Sep-2023

60K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.