1. 程式人生 > >JAVA基礎學習之路(六)數組與方法參數的傳遞

JAVA基礎學習之路(六)數組與方法參數的傳遞

就是 .com 另一個 AS oid span 參數 spa nbsp

通常,向方法中傳遞的都是基本數據類型,而向方法中傳遞數組時,就需要考慮內存的分配

public class test2 {
    public static void main(String args[]) {
        int arr[] = new int[] {9, 1, 2, 3, 4, 7, 8, 6, 5 };
        sort(arr);
        for(int i=0; i<arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
    
    public
static void sort(int arr[]) {//冒泡排序 for (int x= 0; x<arr.length; x++) { for (int y=0; y<arr.length-1; y++) { if (arr[y] > arr[y+1]) { int temp; temp = arr[y]; arr[y] = arr[y+1]; arr[y
+1] = temp; } } } } }

向方法之中傳遞數組,或者將一個數組的值傳給另一個數組,都會產生新的棧內存。引用之中對數組的改變會影響到原數組(其實就是在原數組的堆內存上操作)。當引用操作完成之後,引用產生的占內存不再只想原數組的堆內存。

技術分享圖片

JAVA基礎學習之路(六)數組與方法參數的傳遞