`
鞠文婷
  • 浏览: 16295 次
  • 性别: Icon_minigender_2
  • 来自: 江苏南通
社区版块
存档分类
最新评论

传值&传址之异同小析

阅读更多

        传值or传址,这是一个问题,也是一个比较简单的问题。

        一般人们学习时,总喜欢把问题细节化,对于两个事物,非要追根究底,找出其不同之处。其实准确说来,传址也是一种传值,不过传的是地址的值而已,非人脑所能轻易识别,因此区别开来也是有理可循的。

       关于这个话题,首先必须说明的一点就是:String只传值不传址!

       值传递的一个简单例子:

public class swap {
	public void swap(int i,int j){
		int temp=i;
		i=j;
		j=temp;
	}
}
public class Manager {
	/**
	 * 入口点函数
	 * @param args
	 */
	public static void main(String[] args){
		swap st=new swap();//创建对象
		int i=100;
		int j=20;
		System.out.println("First:i ~ j = "+i+" ~ "+j);//第一次输出
		//调用方法,在changeInt中改变i的值
		st.swap(i,j);
		System.out.println("Second:i ~ j = "+i+" ~ "+j);//第二次输出
	}
}

 输出结果:

First:i ~ j = 100 ~ 20
Second:i ~ j = 100 ~ 20

       在这个例子中,swap的作用就是将 i 和 j 的值互换,而从结果来看并未做到这点。 因为基本数据类型int传的是值。其实想要理解这个例子的话,可以将swap函数添加int返回值,返回 i ,并在此函数中输出 i ,就会发现在First和Second中间会输出一个:i = 20;这便可充分说明调用了swap(i,j);只是改变了其在class swap中的值,对Manager中的参数并无影响。

       而若要证明String只传值不传址,只需定义一个String str=new String("abc");然后再定义一个类将str值赋给属性str,代码如下;

String str=new String("abc");
		test2 te=new test2(str);
		te.print();
		str="def";
		System.out.println("str2 = "+str);

 test2类中

String str;
	public test2(String str){
		this.str=str;
	}
	public void print(){
		System.out.println("str = "+str);
	}

 由String传值可知结果:

str = abc
str2 = def

 在此不多做赘述。

 

址传递又称引用传递,所有用class,interface,abstract class定义的类和接口以及数组都属于引用类型。想看址传递的具体表现形式,只需自定义一个函数,然后用其创建对象,结果显而易见。举例如下:

public static void main(String[] args){
		Student st1=new Student();
		st1.setName("A");
		Student st2=new Student();
		st2.setName("B");
		Student st3=new Student();
		st3.setName("C");
		//进行交换
		st1=st2;
		st2=st3;
		st3=st1;
		String name=st3.getName();
		System.out.println("The name of st3 now is: "+name);

结果为“The name of str3 now is: B”, 从结果可看出,st3最终指向了st2对象,此处为传址。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics