只要记住,对象是传引用的就行。而基本数据类型是传值的。 1. 如果是下面的方式,那么Test中的int值也是可改的。 2. 如果Integer中也有一个int的类变量,那它的值也是可换的。 3. 如果在方法中只能对方法的参数(对象)本身操作,是永远不能改变这个方法外的这个参数的引用的。因为方法传递的是这个引用的一个拷贝。public class IntegerTest { public static void main(String[] args) { Test A = new Test(); Test B = new Test();
A.setValue(10); B.setValue(12);
IntegerTest tt = new IntegerTest(); System.out.println("Before A = " + A.getValue()); System.out.println("Before B = " + B.getValue()); tt.swap(A, B); System.out.println("After A = " + A.getValue()); System.out.println("After B = " + B.getValue());
} public void swap(Test A, Test B) { int tmp = A.getValue(); A.setValue(B.getValue()); B.setValue(tmp); } } class Test { int a; public void setValue(int a) { this.a = a; } public int getValue() { return a; } }Before A = 10 Before B = 12 After A = 12 After B = 10
你说的是不是如何让a,b互换??
a= a+b;
b= a-b;
a= a-b;
public static void swap(int a,int b){} 不行
public static void swap(Integer a, Integer b){} 不行方法名已经定死了 不能更改 用数组入参不行 返回值不行 既然都这样"定死了",你也就死了互换这条心了.
因为java只有值传递
public static void swap(int a,int b){}
public static void swap(Integer a, Integer b){}
都不行!!!
我不是限制你非不能用temp,1楼那个跟temp本质相同,返回void死活是传不出来的,你试了就知道了
你可以再里边调用一个有返回值的方法public static void swap(int a,int b){ swap2(a,b)
} public static int swap2(int a,int b){
}
但这种人肯定脑壳有包
1. 如果是下面的方式,那么Test中的int值也是可改的。
2. 如果Integer中也有一个int的类变量,那它的值也是可换的。
3. 如果在方法中只能对方法的参数(对象)本身操作,是永远不能改变这个方法外的这个参数的引用的。因为方法传递的是这个引用的一个拷贝。public class IntegerTest { public static void main(String[] args) {
Test A = new Test();
Test B = new Test();
A.setValue(10);
B.setValue(12);
IntegerTest tt = new IntegerTest();
System.out.println("Before A = " + A.getValue());
System.out.println("Before B = " + B.getValue());
tt.swap(A, B);
System.out.println("After A = " + A.getValue());
System.out.println("After B = " + B.getValue());
}
public void swap(Test A, Test B) {
int tmp = A.getValue();
A.setValue(B.getValue());
B.setValue(tmp);
}
}
class Test {
int a;
public void setValue(int a) {
this.a = a;
}
public int getValue() {
return a;
}
}Before A = 10
Before B = 12
After A = 12
After B = 10