Java 如何用方法交换两个变量的值

在学习C++的时候,我们需要学习如何用指针和方法来交换两个变量的值,比如swap(int*, int*)。而当我学习Java的时候,因为没有指针,所以我们需要另求他法。这引起了我下面的思考:

(1)方法不能修改基本类型的参数

例如swap(int a, int b); 无论方法内如何修改a和b的值,原来的a和b都不会改变。
public class SwapDemo01 {

	public static void main(String[] args) {
		/**
		 * 方法不能改变基本类型的参数
		 */
		int a = 1;
		int b = 2;
		swap(a, b);
		System.out.println("在main()方法内:");
		System.out.println("a: " + a);
		System.out.println("b: " + b);
	}

	public static void swap(int a, int b) {
		a ^= b;
		b ^= a;
		a ^= b;
		System.out.println("在swap()方法内:");
		System.out.println("a: " + a);
		System.out.println("b: " + b);
	}
结果如下:
在swap()方法内:
a: 2
b: 1
在main()方法内:
a: 1
b: 2

(2)方法可以修改对象参数的状态

当对象作为参数传递给方法时,在方法内部,可以用该对象的公共方法来修改对象的状态(或内容)。
public class SwapDemo02 {

	public static void main(String[] args) {
		/**
		 * 方法可以改变对象参数的状态
		 */
		StringBuffer str1 = new StringBuffer("Hello");
		StringBuffer str2 = new StringBuffer("World");
		swap(str1, str2);
		System.out.println("在main()方法内:");
		System.out.println("str1: " + str1.toString());
		System.out.println("str2: " + str2.toString());
	}

	public static void swap(StringBuffer str1, StringBuffer str2) {
		StringBuffer temp = new StringBuffer(str1.toString());
		str1.delete(0, str1.length());
		str1.append(str2.toString());
		str2.delete(0, str2.length());
		str2.append(temp.toString());
		System.out.println("在swap()方法内:");
		System.out.println("str1: " + str1.toString());
		System.out.println("str2: " + str2.toString());
	}
结果如下:
在swap()方法内:
str1: World
str2: Hello
在main()方法内:
str1: World
str2: Hello
可以看到,swap方法已经成功交换了两个字符串的内容。

(3)方法不能使一个对象参数指向一个新的对象

在上面的第二个方法中,我们通过公共方法来修改对象,不是挺麻烦的吗?为什么不直接交换两个对象呢?或者说让对象互相指向对方,不行吗?下面的测试告诉你,确实不行。
public class SwapDemo03 {

	public static void main(String[] args) {
		/**
		 * 方法不能使一个对象参数指向一个新的对象
		 */
		String str1="Hello";
		String str2="World";
		swap(str1, str2);
		System.out.println("在main()方法内:");
		System.out.println("str1: " + str1);
		System.out.println("str2: " + str2);
	}
	
	public static void swap(String str1, String str2) {
		String temp = str1;
		str1 = str2;
		str2 = temp;
		System.out.println("在swap()方法内:");
		System.out.println("str1: " + str1);
		System.out.println("str2: " + str2);
	}

}
结果如下:
在swap()方法内:
str1: World
str2: Hello
在main()方法内:
str1: Hello
str2: World
可以看到,在swap方法内,两个String指向的字符串已经改变了,而main方法中两个字符串并没有改变。

(4)总结规律

通过上面的实验,我们可以知道对于基本类型,参数传递的是变量的值,方法无法改变原变量的值。对于对象,参数传递的是对象的地址,我们可以根据对象的地址改变对象的状态,但是不能改变原对象的地址。从内存管理的角度来讲,对象的名称和地址是保存在栈内的,对象的内容状态是保存在堆中的,栈内的地址指向堆内的对象状态。当对象作为参数时,相当于把对象的地址复制一份给方法,方法可以根据地址改变对象的状态,也可以修改参数传进来的这个地址,但是不能修改对象本身保存在栈内的地址。

ps.其实可以通过“歪门邪道”改变基本类型的值:将两个变量保存在数组内,将数组传递给方法。这样在方法内交换数组内的值,就真的交换了两个变量的值了。这种方法有点类似于上面第二种方法。

猜你喜欢

转载自blog.csdn.net/Leo_LiangXuYuan/article/details/79070836