public class TestSwap
{
public static void swap(Integer a,Integer b){
Integer t = new Integer(0);
t = a;
a = b;
b = t;
} public static void swap(int a,int b){
int t = 0;
t = a;
a = b;
b = t;
} public static void main(String[] args)
{
Integer a = new Integer(1);
Integer b = new Integer(2);
swap(a,b);
System.out.println(a.intValue()+" "+b.intValue()); int aa = 1;
int bb = 2;
swap(aa,bb);
System.out.println(aa+" "+bb);
}
}为什么两次swap交换值都是不成功的。
int参数的可以理解,可Integer也不成功,这是为什么呢?
{
public static void swap(Integer a,Integer b){
Integer t = new Integer(0);
t = a;
a = b;
b = t;
} public static void swap(int a,int b){
int t = 0;
t = a;
a = b;
b = t;
} public static void main(String[] args)
{
Integer a = new Integer(1);
Integer b = new Integer(2);
swap(a,b);
System.out.println(a.intValue()+" "+b.intValue()); int aa = 1;
int bb = 2;
swap(aa,bb);
System.out.println(aa+" "+bb);
}
}为什么两次swap交换值都是不成功的。
int参数的可以理解,可Integer也不成功,这是为什么呢?
原因很简单,方法内部改变,不会影响方法外面,(我理解为方法的作用域)
实际上,在方法内部,值已经被交换了!
看看下面的代码,你就会明白
package com.yourcompany.fzuser;public class MyTest
{
public static void swap(Integer a,Integer b){
Integer t = new Integer(0);
t = a;
a = b;
b = t;
System.out.println(a+" "+b);
} public static void swap(int a,int b){
int t = 0;
t = a;
a = b;
b = t;
System.out.println(a+" "+b);
} public static void main(String[] args)
{
Integer a = new Integer(1);
Integer b = new Integer(2);
swap(a,b);
System.out.println(a.intValue()+" "+b.intValue()); int aa = 1;
int bb = 2;
swap(aa,bb);
System.out.println(aa+" "+bb);
}
}
Integer a = new Integer(1);//引用 a 指向 假设内存 1
Integer b = new Integer(2);//引用 b 指向 假设内存 2
swap(a,b);public static void swap(Integer a,Integer b){//形参 a ,b.分别指向内存1.2
Integer t = new Integer(0);
t = a;//t指向1
a = b;//a指向2
b = t;//b指向1
//但要注意,这里面的a,b和外面的ab不是同一个引用了。
} //所以执行完方法,外面的a依然指向1,b依然指向2
主要是方法内部的参数的改变不会影响方法的的数据。也就是方法对参数的作用域只限制在方法内!
看看下面的代码,你就明白了!
另外如果你要实现你想要的功能,要用返回值!package com.yourcompany.fzuser;public class MyTest
{
public static void swap(Integer a,Integer b){
Integer t = new Integer(0);
t = a;
a = b;
b = t;
System.out.println(a+" "+b);
} public static void swap(int a,int b){
int t = 0;
t = a;
a = b;
b = t;
System.out.println(a+" "+b);
} public static void main(String[] args)
{
Integer a = new Integer(1);
Integer b = new Integer(2);
swap(a,b);
System.out.println(a.intValue()+" "+b.intValue()); int aa = 1;
int bb = 2;
swap(aa,bb);
System.out.println(aa+" "+bb);
}
}
后者是引用,但是你在交换的过程中改变了引用,也就是说,你的交换使a,b不再指向原先传给他们的地址,而不是改变他们所指的地址上的东西。这是可行的:class ClassPair {
int a,b;
}public static void swap(ClassPair p){
int t = p.a;
p.a = p.b;
p.b = t;
} 但我想你不希望把代码变成这样子,那我也不知道怎么办了。