看板 java 關於我們 聯絡資訊
※ 引述《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
Killercat:直接用這個吧http://tinyurl.com/nl52qxt 07/19 23:23
Killercat:不過這東西本來用途不是這個就是 反正都寫好了 XD 07/19 23:23
Killercat:這本來是為了解決final native_type的一些問題做的 07/19 23:24
NullLife:推文的類別頗酷,推一個~ 07/20 01:06