|
java中其实是有指针的,只不过不同于c++中那么灵活,复杂,可以认为java中的指针是一种“安全指针”,对于其中的参数传递也是一个很麻烦的问题,这里有个小示例,可以参考下。 package src.whu;
public class Yinyong{ public static void main(String args[]){ String str="1234"; char ch1[]={'h','e','l','l','o'}; char ch2[]={'h','e','l','l','o'};
change(str,ch1,ch2); System.out.println("str:"+str); System.out.print("ch1:"); for(int i=0;i<ch1.length;i++) { System.out.print(ch1); } System.out.println(); System.out.print("ch2:"); for(int i=0;i<ch2.length;i++) { System.out.print(ch2); }
}
private static void change(String str,char[] ch1,char ch2[]) { // TODO Auto-generated method stub //str="hello"; str=new String("hello"); ch1=new char[]{'c','e','l','l','o'}; ch2[0]='c'; } }
有兴趣,可以自己看看,输出的结果str,ch1,ch2是多少?
str:1234 ch1:hello ch2:cello
小结:函数调用的本质是一个值传递,关键是形参的类型,数组是指针型的,string是值类型的。 ch2[0]='c';这句话的含义是将ch2所指向的内存中偏移是0的内容变成c,月就是ch2指向的内容发生了改变。 而ch1=new char[]{'c','e','l','l','o'};相当于让ch1指向一个新的数组,并不会改变原有的数组。
|
一共有 2 条评论
我还想知道有哪些形参的类型是引用传递的,谢谢