![](/img/trans.png)
[英]In Java, How much memory is allocated on stack and heap for “new Object()”
[英]How is the memory allocated(stack and heap reference) when an OBJECT array is created?
喜歡
public static student[] arr = new student[10];
現在,student是一個具有一些實例變量name(String)
和age(int)
。 我想知道一旦這條線被執行會發生什么? 所有十個引用都會得到內存還是我必須單獨分配它們? 如果試圖訪問student[5].age
怎么student[5].age
? 我需要知道內存分配狀態..謝謝...............
執行上述語句時,JVM將創建10個連續的內存位置,每個位置足以容納對student
引用。 但是,如果您願意,此數組將不包含任何引用或null
。 當你執行像arr[0] = new student();
語句時arr[0] = new student();
將在堆上創建一個student
對象,其引用將保存在arr[0]
。 請記住,數組也在堆上分配。
因此,一旦你創建了10個student
對象,每個對象將被分配到堆上的某個地方,但它們的引用將存儲在arr
是
public static student[] = new student[10];
一旦該行執行, JVM
為10個學生references
分配內存。
從Arrays的官方文檔中 ,看一下流程。
// declares an array of integers
int[] anArray;
// allocates memory for 10 integers
anArray = new int[10];
// initialize first element
anArray[0] = 100;
創建對象數組時, 只會創建引用變量 。 在您的情況下,學生類的參考變量。
在下圖中,創建了一組參考變量。 然后,您可以稍后將這些引用變量指向實際對象。
public static student[] arr = new student[10];
將為10名學生分配記憶。 這些內存填充為null。
所以在這里你無法訪問student[5].age
因為對實際對象的引用不存在。
我們需要像下面一樣單獨創建Object引用
for(int i=0;i<10;i++){
student[i]= new Student();
}
如果您在創建實際對象引用之前訪問student [5] .age,則將以NullPointerException結束。
所有十個引用都會得到內存還是我必須單獨分配?
您將獲得十個參考空間。 這些引用將初始化為null
。 如果您希望將它們設置為null
以外的任何null
,則必須單獨執行此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.