首先,我们来回顾下C语言中的swap函数设计
传值:不能从根本上交换两数
#include <stdio.h>
void swap(int a, int b) {
int temp;
temp = a; a = b; b = temp;
}
传引用:在C语言中,应该称地址
#include <stdio.h>
void swap(int &a, int &b) {
int temp;
temp = a; a = b; b = temp;
}
那问题来了,java中没有指针的说法,对普通变量也没有引用,那我们要怎么对普通类型的变量进行引用传递呢?
方法一:利用数组
public static void swap(int[] data, int a, int b) {
int temp;
temp = data[a]; data[a] = data[b]; data[b] = temp;
}
方法二(误导):通过java中的包装类Integer进行引用传递,结果:失败,因为java中的包装类不允许改变数据域,个人理解为:java不会提供包装类Integer数据地址,即引用,而是提供表面数据
方法三:定义自己的包装类MyInteger
static class MyInteger {
private int x;
public MyInteger(int x) {
this.x = x;
}
public int getValue(){
return x;
}
public void changeValue(int x) {
this.x = x;
}
}
public static void swap(MyInteger a, MyInteger b) {
int t = a.getValue();
a.changeValue(b.getValue());
b.changeValue(t);
}
方法四:外部内联,直接利用本类
public class Sort {
int a, b;
public Sort(int a, int b) {
this.a = a;
this.b = b;
}
public void swap() {
int temp;
temp = a; a = b; b = temp;
}
}
参考:https://blog.youkuaiyun.com/dadoneo/article/details/6577976