A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

如下代码:
  1. public class SwapTest{
  2.         public static void main(String[] args) {
  3.                 String[] strings=new String[]{"hello","thanks","bye-bye"};
  4.                 swap(strings,1,2);
  5.                 for(String str:strings){
  6.                         System.out.println(str);
  7.                 }
  8.         }
  9.         private static <T> void swap(T[] a, int i, int j) {
  10.          T tmp=a[i];
  11.          a[i]=a[j];
  12.          a[j]=tmp;
  13.         }
  14. }
复制代码

5 个回复

倒序浏览
本帖最后由 陈冲 于 2012-7-15 18:09 编辑
  1. public class SwapTest{
  2.         public static void main(String[] args) {
  3.                 String[] strings=new String[]{"hello","thanks","bye-bye"};
  4.                 swap(strings,1,2);
  5.                 for(String str:strings){
  6.                         System.out.println(str);
  7.                 }
  8.         }
  9.         private static <T> void swap(T[] a, int i, int j) {
  10.          T tmp=a[i]; //定义一个变量,临时存储数组中的元素,以免在交换的时候,数组元素被覆盖
  11.          a[i]=a[j];//将a[j]的值赋给a[i]如果没有上一行定义的tmp变量的话,a[i]会被a[j]覆盖掉,导致a[i]和a[j]元素的值相同
  12.          a[j]=tmp;//将临时存储的a[i]的值赋给a[j]
  13.         }
  14. }
复制代码
以主函数中的数组为例:
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


回复 使用道具 举报
  1. 01.public class SwapTest{

  2. 02.        public static void main(String[] args) {

  3. 03.                String[] strings=new String[]{"hello","thanks","bye-bye"};

  4. 04.                swap(strings,1,2);

  5. 05.                for(String str:strings){

  6. 06.                        System.out.println(str);

  7. 07.                }

  8. 08.        }

  9. 09.        private static <T> void swap(T[] a, int i, int j) {

  10. 10.         T tmp=a[i];//定义临时量,用于对数的存储,将a[i]的值赋值给tmp

  11. 11.         a[i]=a[j];//将a[j]的值赋值给a[i]

  12. 12.         a[j]=tmp;//将tmp的值赋值给a[j]

  13. 13.        }

  14. 14.}

复制代码
回复 使用道具 举报
添加一个图示例:
回复 使用道具 举报
回复 使用道具 举报
swap(strings, 1, 2);    //调用你定义的功能,把strings,数组中1位置,2位置传入该功能
T temp = a;   //定义一个第三方变量,用来临时存储原来角标为i该位置的数据
  a = a[j];   //将角标j位置的变量的值赋给i位置
  a[j] = temp;    //将临时变量存储的值赋给j位置

如下图标号步骤所示

2.jpg (5.94 KB, 下载次数: 25)

2.jpg

评分

参与人数 1技术分 +1 收起 理由
黑马张扬 + 1

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马