如何在 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP