標(biāo)題起的很大,但是我只想講一個(gè)比較容易令我困惑的問(wèn)題困介。
今天在刷一道簡(jiǎn)單的鏈表題目時(shí),又產(chǎn)生了困惑蘸际,這次結(jié)合之前的JVM知識(shí)希望把這個(gè)問(wèn)題徹底解決。
先上代碼
public static Node reverse(Node head){
if(head == null || head.next == null){
return head;
}
Node next = null;
Node pre = null;
while (head != null){
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
代碼很簡(jiǎn)單徒扶,就是一個(gè)反轉(zhuǎn)鏈表粮彤,Node是一個(gè)普通的類(lèi)。
首先我們知道姜骡,JVM中导坟,聲明的對(duì)象引用存儲(chǔ)在棧中,它所代表的實(shí)際對(duì)象存儲(chǔ)在堆中圈澈。
如
Node a = new Node();
a這個(gè)對(duì)象引用存儲(chǔ)在棧中惫周,JVM同時(shí)也在堆中開(kāi)辟了一塊真實(shí)的內(nèi)存存儲(chǔ)這個(gè)Node對(duì)象,
棧中存儲(chǔ)的實(shí)際上是地址康栈,這個(gè)地址指向堆中的內(nèi)存
那么我上面的代碼中
Node next = null;
Node pre = null;
把它們聲明為null递递, 這時(shí)其實(shí)在堆中并沒(méi)有開(kāi)辟內(nèi)存喷橙,但是在棧中,占用了棧的空間登舞,只不過(guò)里面存儲(chǔ)的是null 值贰逾。
同時(shí)在java里對(duì)象傳遞的時(shí)候,傳遞的都是引用(也就是對(duì)象的地址)菠秒,這比傳遞整個(gè)對(duì)象高效的多疙剑。而基礎(chǔ)類(lèi)型,int践叠,double等傳遞的才是值言缤。
Node next = null;
Node pre = null;
while (head != null){
next = head.next;
head.next = pre;
pre = head;
head = next;
}
所以在這個(gè)循環(huán)中,一開(kāi)始head.next被賦值為pre (也就是null)
緊接著 pre=head , pre在棧中原本是null禁灼,現(xiàn)在變成了一個(gè)地址管挟,這個(gè)地址指向了堆中的head實(shí)際對(duì)象。而head.next并沒(méi)有改變匾二,在棧中暫時(shí)還是null哮独。