第一种:添加中间变量,算是最经典最简易的一种了。
//添加一个中间变量 int x = 1, y = 2; int z; z = x;x = y;y = z; System.out.println(x+","+y);
虽说是最容易想到的一种,但是不建议使用,原因无他,太low。
第二种,通过加减实现。
//加减 x = 1;y = 2; x = x + y; y = x - y; x = x - y; System.out.println(x+","+y);
第三种,异或,比较合理却很少见的一种。
//异或 x = 1; y = 2; x = x ^ y; y = x ^ y; x = x ^ y; System.out.println(x+","+y);
第四种,通过对象引用交换两个参数值
package cn.tedu.demo;
import java.util.Arrays; //通过对象引用交换两个参数值 public class Demo14 { private Object num; public Demo14(Object num) { super(); this.num = num; } public Object getNum() { return num; } public void setNum(Object num) { this.num = num; } public static void test1(Demo14 a,Demo14 b){ Object nums = a.getNum(); a.setNum(b.getNum()); b.setNum(nums); System.out.println(a.getNum()+","+b.getNum()); } public static void main(String[] args) { // TODO Auto-generated method stub Demo14 a = new Demo14(1); Demo14 b = new Demo14(2); test1(a,b); } }