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

作者: adrianshum (Alien)   2014-07-19 11:55:02
※ 引述《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());
}
}
作者: Killercat (殺人貓™)   2014-07-19 23:23:00
直接用這個吧http://tinyurl.com/nl52qxt不過這東西本來用途不是這個就是 反正都寫好了 XD這本來是為了解決final native_type的一些問題做的
作者: NullLife (廢材大叔有點累)   2014-07-20 01:06:00
推文的類別頗酷,推一個~

Links booklink

Contact Us: admin [ a t ] ucptt.com