public class Test0001 { public static void main(String[] args) { int a = 10; int b = 20; (new Test0001()).Swap(a,b); } void Swap(int a, int b) { int temp; temp = a; a = b; b = temp; System.out.println("new a=" + a + " b=" + b); } }
to stefli: 把print放到main函数里就知道了 class MyClass{ int a; int b; } void swap(MyClass c){ int d = c.a; c.a=c.b; c.b = d }
java是严格的值传递,SWAP不可能
在 C/C++ 中要交换2个变量就要 传地址, 而Java 是通过传变量来实现交换的, Java 也不支持 取地址 & int a=10; int b=20; public void swap( int num1, int num2 ) { int temp;
temp = num1; num1 = num2; num2 = temp; }
swap( a, b ); 其实只在 swap 方法中改变了 a 与 b 的值. 在 swap 方法外 a=10; b=20; 仍然没变.因为传的不是对象.
{
int temp=a;a=b;b=temp;
}
同意楼上,及楼上的楼上的楼上
{
public static void main(String[] args)
{
int a = 10;
int b = 20;
(new Test0001()).Swap(a,b);
} void Swap(int a, int b) {
int temp;
temp = a;
a = b;
b = temp;
System.out.println("new a=" + a + " b=" + b);
}
}
把print放到main函数里就知道了
class MyClass{
int a;
int b;
}
void swap(MyClass c){
int d = c.a;
c.a=c.b;
c.b = d
}
Java 也不支持 取地址 & int a=10;
int b=20; public void swap( int num1, int num2 )
{
int temp;
temp = num1;
num1 = num2;
num2 = temp;
}
swap( a, b ); 其实只在 swap 方法中改变了 a 与 b 的值. 在 swap 方法外 a=10; b=20; 仍然没变.因为传的不是对象.