本帖最后由 陈冲 于 2012-7-15 18:09 编辑
- public class SwapTest{
- public static void main(String[] args) {
- String[] strings=new String[]{"hello","thanks","bye-bye"};
- swap(strings,1,2);
- for(String str:strings){
- System.out.println(str);
- }
- }
- private static <T> void swap(T[] a, int i, int j) {
- T tmp=a[i]; //定义一个变量,临时存储数组中的元素,以免在交换的时候,数组元素被覆盖
- a[i]=a[j];//将a[j]的值赋给a[i]如果没有上一行定义的tmp变量的话,a[i]会被a[j]覆盖掉,导致a[i]和a[j]元素的值相同
- a[j]=tmp;//将临时存储的a[i]的值赋给a[j]
- }
- }
复制代码 以主函数中的数组为例:
strings={"hello","thanks","bye-bye"}
strings[0]="hello",string[1]="thanks",string[2]="bye-bye"
在调用swap()方法时,交换过程如下:
定义tmp
tmp=string[1];//tmp="thanks"; strings={"hello","thanks","bye-bye"}
string[1]=string[2];//strin1g="bye-bye";strings={"hello","bye-bye","bye-bye"}
string[2]=tmp;//string[2]="thanks";strings={"hello","bye-bye","thanks"}
所以,交换完毕后的数组是strings={"hello","bye-bye","thanks"}
输出结果为
hello
bye-bye
thanks
|