Java中的Swap,如何实现?
2024-10-08 04:12:33
程序员都知道,在C/C++里面交换值的方法:
void swap(int &a,int &b)
{
int temp;
temp=a;
a=b;
b=temp;
}
但是在Java中这种方法是行不通的,因为Java对普通类型的变量是不支持引用传递的。
怎么办呢?
1.可以像下面这样通过传数组(也属于传值)的方法来完成交换(很多排序算法就是这样实现)。
public static void swap(int[] data,int a,int b){
int temp=data[a];
data[a]=data[b];
data[b]=temp;
}
package pkg2020华南虎; /**
*
* @author yl
*/
public class SwapValue { public static void main(String[] args) {
SwapValue sv = new SwapValue();
int[] num = new int[2];
num[0] = 20;
num[1] = 30;
sv.swap(num, 0, 1);
System.out.println("num1,num2:" + num[0] + "," + num[1]);
} public static void swap(int[] data, int a, int b) { int temp = data[a];
data[a] = data[b];
data[b] = temp;
}
}
或者
package pkg2020华南虎; /**
*
* @author yl
*/
public class SwapValue { public static void main(String[] args) { int[] num = new int[2];
num[0] = 20;
num[1] = 30;
swap(num, 0, 1);
System.out.println("num1,num2:" + num[0] + "," + num[1]);
} public static void swap(int[] data, int a, int b) { int temp = data[a];
data[a] = data[b];
data[b] = temp;
}
}
注意:数组排序从0开始。
2.也可以通过重新定义个类(在Java中我们可以通过使用int的包装类——integer,然后将其作为值得引用传到函数中,但这个integer包装类也不允许你来改变它的数据域;但这不妨碍我们用自己的包装类,比如说下面实现的MyInteger():
package pkg2020华南虎; /**
*
* @author yl
*/
//MyInteger:于Integer类似,但是其对象可以变值
class MyInteger { private int x;//将x作为唯一的数据成员 public MyInteger(int xIn) {
x = xIn;
}//构造器 public int getValue() {
return x;
}//得到值 public void insertValue(int xIn) {
x = xIn;
}//改变值
} public class SwapValue02 { static void swap(MyInteger xWrap, MyInteger yWrap) {
int temp = xWrap.getValue();
xWrap.insertValue(yWrap.getValue());
yWrap.insertValue(temp);
} public static void main(String[] args) {
int a = 23, b = 25;
MyInteger aWrap = new MyInteger(a);
MyInteger bWrap = new MyInteger(b);
swap(aWrap, bWrap);
a = aWrap.getValue();
b = bWrap.getValue();
System.out.println("a,b is: " + a + "," + b);
}
}
3.由于Java中的参数传递都是采用的值传递方式,这不妨碍我们用swap的时候采用外部内联的方式:
package pkg2020华南虎; /**
*
* @author yl
*/
public class SwapValue03 { int i, j; public static void main(String[] args) {
SwapValue03 sv = new SwapValue03(1, 2);
sv.swap();
System.out.println("i,j =" + sv.i + "," + sv.j);
} public SwapValue03(int i, int j) {//构造方法
this.i = i;
this.j = j;
} public void swap() {
int temp = i;
i = j;
j = temp;
}
}
最新文章
- fragment的切换(解决REPLACE的低效)
- Android Studio2.0 教程MAC版 -快捷键篇
- linux下编译安装boost库
- 【T电商】 maven初识
- Eclipse 运行多个Tomcat实例
- Windows VC++常见问题汇总
- Orchard中的多语言功能
- 【Python基础】计算项目代码行数
- SDN学习之RYU源码安装
- c#结构体、打他table、excel、csv互转
- FeignClient注解及参数
- node获取windows pc 机器的标示
- 11-部署Heapster插件
- 把自己的代码发布到npm(npm publish)
- 人生苦短之我用Python篇(socket编程)
- 单点登录(五)-----遇到问题-----cas server 源码部署tomcat运行报错BeanCreationException:Error creating bean with name 's
- js延迟加载优化页面响应速度
- BZOJ 2707: [SDOI2012]走迷宫 拓扑+高斯消元+期望概率dp+Tarjan
- 【hdoj_2111】SavingHDU
- centos6.4编译hadoop2.4源码