coolwaterld的专栏

起因:

写android的程序时,要写一大堆赋值

txtYaw = (TextView)findViewById(R.id.txtYaw); txtPitch = (TextView)findViewById(R.id.txtPitch); txtRoll = (TextView)findViewById(R.id.txtRoll);

于是将 (TextView)findViewById封装为函数:

private void setTextViewID(TextView tv,int id) { tv = (TextView)findViewById(id); }

setTextViewID(RVP,R.id.RVP);

看起来更整洁,但是发现在RVP.seText报错:

E/AndroidRuntime﹕ FATAL EXCEPTION: main java.lang.NullPointerException

发现RVP为null

于是恶补了以下java 函数参数,以“java 函数 参数 传递“为关键字搜索,发现讲的不清不出,还是搜了stack overflow

以下为主要内容:

Java is always pass-by-value. The difficult thing to understand is thatJava passes objects as references and those references are passed by value.

我的理解:java 函数 参数 传递对象时,,函数内部可以修改对象的属性,但是重新给对象的引用赋值不行,因为引用本身为传值。

It goes like this:

foo}}dd d}

In this example aDog.getName() will still return "Max". The valueaDog within main is not overwritten in the function foo with the Dog "Fifi" as the object reference is passed by value. If it were passed by reference, then theaDog.getName() in main would return "Fifi" after the call tofoo.

Likewise:

fooaDogd d}再有就是传递数组也是同样道理:数组内部可以修改,new一个新的数组不行 public class ArrayPar { public static void main(String [] args) { int x=1; int y[]={1,2,3}; changeValue(x,y); System.out.println("outside changeValue x="+x+",y[0]="+y[0]); changeRef(y); System.out.println("Outside changeRef y[0]="+y[0]); } public static void changeValue(int num,int [] array) { num=100; array[0]=100; } public static void changeRef(int [] array) { array = new int[3]; array[0] = 123; System.out.println("inside changeRef array[0]="+array[0]); } }结果:java ArrayPar outside changeValue x=1,y[0]=100inside changeRef array[0]=123Outside changeRef y[0]=100//不变回到最初的问题,java缺少宏 或者 inline等 文本替换的方式变通策略可以采用 Sting to code 的方式,不过代价比较高,得不偿失

于是夜莺会在黎明到来之前勇敢的将胸膛顶住蔷薇的刺,

coolwaterld的专栏

相关文章:

你感兴趣的文章:

标签云: