Re: [問題] 取得基本型別的reference
※ 引述《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
07/19 23:23, 1F
→
07/19 23:23, , 2F
07/19 23:23, 2F
→
07/19 23:24, , 3F
07/19 23:24, 3F
推
07/20 01:06, , 4F
07/20 01:06, 4F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):
java 近期熱門文章
PTT數位生活區 即時熱門文章