在程序开发的过程,要交换两个变量的内容,是一种比较常见的事情。在排序算法中,就有一种就叫做“交换排序法”。在所有的排序算法,交换要排序的集合中的两个元素,几乎是必须的过程。在Java中交换两个元素的内容,如果你是程序员新手,你可能碰到意想不到的问题。

众所周知,java和C、C++中都不能通过值传递的方式实现两个整数的交换。

即下面的函数是不能成功交换两个整数的,

1 public void swap1(int a,int b){ //值参数传递不能实现交换两个整数
2 intt;
3 t =a;
4 a =b;
5 b =t;
6 }

在C++,可以通过引用或者指针来实现两个整数的交换,实质上是通过地址传递来实现两个整数的交换的。

void swap2(int &a,int &b) //引用传递
{
inttemp;
temp =a;
a =b;
b =temp;
}

还可以通过指针来实现两个整数的交换

1 void swap2(int *a,int *b)//指针,地址传递
2 {
3 inttemp;
4 temp = *a;
5 *a = *b;
6 * b =temp;
7 }

那么java中又是如何实现两个整数的交换呢?

方法1:

通过数组方式交换:

如果一定要通过一个   method   来实现,下面的形式也许可以:

1 void swap(int[] a) {
2 if (a == null || a.length != 2)
3 throw newIllegalArgumentException();
4 int temp = a[0];
5 a[0] = a[1];
6 a[1] =temp;
7 }

代码实例如下:

//实现个整数的交换
public classSwapInteger {
public static void swap(inta[]){
//数组传递实现交换两个整数
intt;
t = a[0];
a[0] = a[1];
a[1] =t;
}
public static voidmain(String args[]){
int []a = new int[2];
a[0] = 3;
a[1] = 4;
swap(a);
System.out.println(a[0] + "/t" + a[1]);
}
}

2)方法2:

构造对象,将a,b作为对象的属性,然后操作对象,最后获得对应的属性。

有人说可以用Integer类来实现,这是错误的说法。

理由如下:

Integer不行,

1、Integer本身是值对象(value   object),不能修改它的内容(找找哪个方法能修改它的内容?)。实际上,串对象String都不能改变;

2、就算Integer本身可以修改,自动装箱、拆箱也不灵:

void   exchange(   Integer   ao,   Integer   bo   )   {   交换ao和bo中的实际数据   }
int   a,   b;
exchange(   a,   b   );   //   自动装箱机制生成了两个临时对象,不过调用返回时不能传回a和b。

最多只能这样:

Integer   ao=a;
Integer   bo=b;
exchange(   ao,   bo   );
a   =   ao;
b   =   bo;

例题:交换JAVA数组中两数

该代码实现功能:

1.接受用户输入10个整数,并存入Array

2.将Array中的最大值与最小值交换位置

java程序如下:

1 importjava.util.Scanner;
2 public classSwapNumber {
3 public static voidmain(String[] ar) {
4
5 Scanner input = newScanner(System.in);
6
7 int maxIndex = 0; //标记最大值索引
8 int minIndex = 0; //标记最小值索引
9 int numbers[] = new int[10]; //声明数组接受用户输入
10 System.out.println("请输入十个数字:");
11 //循环接收
12 for (int i = 0; i < numbers.length; i++) {
13 numbers[i] =input.nextInt();
14 }
15 int temp = 0; //临时变量
16 int max = numbers[0]; //标记最大值
17 int min = numbers[0]; //标记最小值
18 //查找最大,最小索引
19 for (int i = 1; i < numbers.length; i++) {
20 if (numbers[i] >max) {
21 max = numbers[i]; //一定要将该值赋给max!!!!!
22 maxIndex =i;
23 }
24 if (numbers[i] 
25 min =numbers[i];
26 minIndex =i;
27 }
28 }
29 //输出排序后效果
30 for (inta : numbers) {
31 System.out.print(a + "/t");
32 }
33 //进行交换操作
34 temp =numbers[maxIndex];
35 numbers[maxIndex] =numbers[minIndex];
36 numbers[minIndex] =temp;
37
38 //输出排序后效果
39 System.out.println("排序后,输出:");
40 for (int i = 0; i < numbers.length; i++) {
41 System.out.print(numbers[i] + "/t");
42 }
43 }
44 }