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


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

 

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

 

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM