Re: [問題] 取得基本型別的reference

看板java作者 (Alien)時間11年前 (2014/07/19 11:55), 編輯推噓2(202)
留言4則, 2人參與, 最新討論串2/2 (看更多)
※ 引述《lordfish62 (阿瑜)》之銘言: : 版上的各位好, : 想請教各位如何在java中取得基本型別如:int, char, ... : 的reference呢? : 寫個簡單的java code如下: : public class Test : { : public void foo(int m) : { : m += 1; : System.out.println(m); : } : public static void main(String[] args) : { : int temp = 0; : System.out.println(temp); : new Test().foo(temp); : System.out.println(temp); : } : } : 輸出的結果是: : 0 : 1 : 0 : 因為在java中基本型別的變數名稱並不是reference : 我想問的是如何可以取得temp的reference傳進函式裡 : 使得輸出變成: : 0 : 1 : 1 : 解釋的有點亂,不知道我的表達是否清楚== 沒有直接的方法,唯一可以做的 workaround 只有類似這種: class IntHolder { int i = 0; public IntHolder(int i) { this.value = i; } // getter, setter } class Test { public void foo(IntHolder intHolder) { intHolder.setValue(intHolder.getValue() + 1); } public static void main(String[] args) { IntHolder temp = new IntHolder(0); System.out.println(temp.getValue()); new Test().foo(temp); System.out.println(temp.getValue()); } } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 223.19.42.87 ※ 文章網址: http://www.ptt.cc/bbs/java/M.1405742105.A.F7D.html

07/19 23:23, , 1F
直接用這個吧http://tinyurl.com/nl52qxt
07/19 23:23, 1F

07/19 23:23, , 2F
不過這東西本來用途不是這個就是 反正都寫好了 XD
07/19 23:23, 2F

07/19 23:24, , 3F
這本來是為了解決final native_type的一些問題做的
07/19 23:24, 3F

07/20 01:06, , 4F
推文的類別頗酷,推一個~
07/20 01:06, 4F
文章代碼(AID): #1JoUmPzz (java)
討論串 (同標題文章)
文章代碼(AID): #1JoUmPzz (java)