这道题之前在c语言中我们有做过,这里我们用三种方法求解
方法一:创建临时变量
public class Text {
public static void main(String[] args) {
int a=10;
int b=20;
int tmp=0;
tmp=a;
a=b;
b=tmp;
System.out.println("a="+a+"\n"+"b="+b);
}
}
方法二:不创建临时变量,增减法
public class Text {
public static void main(String[] args) {
int a=10;
int b=20;
a=a+b;
b=a-b;
a=a-b;
System.out.println("a="+a+"\n"+"b="+b);
}
}
方法三:进行异或运算实现两数交换
public class Text {
public static void main(String[] args) {
int a=10;
int b=20;
a=a^b;
b=a^b;
a=a^b;
System.out.println("a="+a+"\n"+"b="+b);
}
}

方法四
Integer包装类来实现
但是由于Integer是不可变的,所以我们可以自己做一个包装类
class MyInteger{
private int value;
public MyInteger(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
public class Swap {
static void swap(MyInteger x, MyInteger y){
MyInteger tmp = new MyInteger(x.getValue());
x.setValue(y.getValue());
y.setValue(tmp.getValue());
}
public static void main(String[] args) {
MyInteger a = new MyInteger(10);
MyInteger b = new MyInteger(20);
swap(a,b);
System.out.println(a.getValue());
System.out.println(b.getValue());
}
}
这篇博客介绍了如何在Java中实现两个整数的交换,包括使用临时变量、增减法以及异或运算的方法,并提及了对于Integer包装类的不可变性及其应用。
623





