Re: [問題] pass-by-value的問題
※ 引述《newjoy (職業格鬥家)》之銘言:
: public class test {
: private int index = 0;
: public test()
: {
: this.index = 0;
: }
: public void setIndex(int index)
: {
: this.index = index;
: }
: public int getIndex()
: {
: return this.index;
: }
: public static void assignT(test t)
: {
: t = new test();
: }
: public static void main(String[] args){
: test t1 = new test();
: t1.setIndex(9);
: assignT(t1);
: System.out.println("value : "+t1.getIndex());
: }
: }
: 如果傳入function 裡面的是 object的 reference,
: 那為什麼執行assignT之後
: 印出來的值一樣是9而不是0??
: 假設 t1 的位址是 0xAA
: 那傳進 assignT 裡的 t 會是copy的一份 0xAA的 object 位址
: 然後 t = new test(); 會把0xAA的內容指向一個新的 test實體,
: 這樣理解有錯嗎?
------------------------------------------------------------------------------
after "assignT(t1);"
before "t = new Test();"
┌─────┐0x00f00000 in stack memory
│0x10f10000│t1 @ main
└┼────┘
└─────┐┌───────────┐
↓↓ │
┌─────┐0x10f10000 in heap memory │
│..........│an instance of class test │
└─────┘which is created @ main │
┌──────────────────┘
┌┼────┐0x00f20000 in stack memory
│0x10f10000│t @ assignT [when main call assignT]
└─────┘the value is passed by main
------------------------------------------------------------------------------
after "t = new Test();"
┌─────┐0x00f00000 in stack memory
│0x10f10000│t1 @ main
└┼────┘
└─────┐
↓
┌─────┐0x10f10000 in heap memory
│..........│an instance of class test
└─────┘which is created @ main
┌─────┐0x00f20000 in stack memory
│0x10f30000│t @ assignT [after "t = new Test();"]
└┼────┘the value is assigned
└─────┐
↓
┌─────┐0x10f30000 in heap memory
│..........│an instance of class test
└─────┘which is created @ assignT
------------------------------------------------------------------------------
back to main
┌─────┐0x00f00000 in stack memory
│0x10f10000│t1 @ main
└┼────┘
└─────┐
↓
┌─────┐0x10f10000 in heap memory
│..........│an instance of class test
└─────┘which is created @ main
┌─────┐0x10f30000 in heap memory
│..........│an instance of class test
└─────┘which is created @ assignT
It becomes a garbage.
The reason is nobody can access this instance.
------------------------------------------------------------------------------
如果我沒有理解錯的話,
除了, main 自己以外,
沒有其它的 method 可以改變 t1 @ main 的值。
--
" 愛 "是"喜歡"的累積!
"喜歡"是"感覺"的累積!
"感覺"是"緣份"的累積!
"緣份"是"前世"的累積!
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 59.104.29.8
推
11/05 14:21, , 1F
11/05 14:21, 1F
推
11/05 21:49, , 2F
11/05 21:49, 2F
→
11/05 21:52, , 3F
11/05 21:52, 3F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):