基本概念
棧內存
所謂的棧內存就是存儲進程在運行過程中變量的內存空間
堆內存
所謂的堆內存就是存儲系統中數據的內存空間
數組相關的引用傳遞
先來看一段代碼
public class ArrayDemo {public static void main(String[] args) {int[] x = null;x = new int[3];System.out.println(x.length);x[0] = 10 ; // 數組第一個元素x[1] = 20 ; // 數組第二個元素x[2] = 30 ; // 數組第三個元素for (int i = 0; i<x.length ; i++) {System.out.println(x[i]) ; // 通過循環控制索引下標更改}}
}
通過上述代碼我們來看一下上述變量在內存空間中式如何分配的
同時,多個占內存也可以指向同一塊對內存,如下代碼
public class ArrayDemo{public static void main(String[] args) {int[] x = null ;int[] temp = null ; // 聲明對象x = new int[3] ;System.out.println(x.length) ;x[0] = 1 ; // 數組第一個元素x[1] = 2 ; // 數組第二個元素x[2] = 3 ; // 數組第三個元素for (int i = 0; i<x.length ; i++) {System.out.println(x[i]) ; // 通過循環控制索引下標更改}temp = x ; //如果要發生引用傳遞,不要出現[]temp[0] = 55 ; // 修改數據System.out.println(x[0]) ;}
}
相信看了這幅圖之后,就會理解java中不同的棧變量指向相同的堆變量在內存中是如何分配的了