java 跟c++不同,java的方法参数都是传值,没有传引用。很多人都以为是传引用,而且这种错误的观点很普遍,今天在这里具体分析一下。方法参数有基本类型,如int等,另外一种类型是object,对象。详细说一下方法参数是对象的,跟c++不同的是,java方法参数传对象,传的是对这个对象引用的一份拷贝,即地址值,跟原来的引用都是指向同一个对象。所以说,java方法参数传的都是值。
程序一 传的对象值是改变的。
public class test
{
public test()
{
int [] count={5};
change(count);
system.out.println(count[0]);
}
public void change(int [] counts)
{
counts[0]=6;
system.out.println(counts[0]);
}
public static void main(string [] args)
{
test t=new test();
}
}
程序一中,输出结果都是6,change(count); 把对象的一份引用拷贝传给change(),这个拷贝跟原来的引用都是指向同一个对象。所以改变引用拷贝的值,对象的值也跟着改变。
程序2,传的对象值不改变
class foo{
int i=0;
}
public class a{
public static void main(string args[]){
foo f=new foo();
add(f);
system.out.println(f.i);
}
public static void add(foo f){
f=new foo();
f.i++;
}
}
class foo{
int i=0;
}
public class a{
public static void main(string args[]){
foo f=new foo();
add(f);
system.out.println(f.i);
}
public static void add(foo f){
f=new foo();
f.i++;
}
}
输出结果是0
程序2中,也是传一份引用的拷贝,但在 add()方法中,f=new foo(); new出了一个新的对象,所以引用的拷贝指向了一个新的object。原来的值还是没有改变。
程序3 string 不改变,数组改变
public class example{
string str=new string(“good”);
char[]ch={a,b,c};
public static void main(string args[]){
example ex=new example();
ex.change(ex.str,ex.ch);
system.out.print(ex.str+” and “);
sytem.out.print(ex.ch);
}
public void change(string str,char ch[]){
str=”test ok”;
ch[0]=g;
}
}
public class example{
string str=new string(“good”);
char[]ch={a,b,c};
public static void main(string args[]){
example ex=new example();
ex.change(ex.str,ex.ch);
system.out.print(ex.str+” and “);
sytem.out.print(ex.ch);
}
public void change(string str,char ch[]){
str=”test ok”;
ch[0]=g;
}
}
程序3输出的是 good and gbc.
string 比较特别,是因为java在传string的时候把string当成基本类型来处理 。所以值是不变的。