数组复制的三种方法

本文将给出三种实现数组复制的方法 (以复制整数数组为例)。

方法一 : 循环遍历赋值达到复制数组的效果

     /**
  * 循环遍历赋值达到复制数组的效果
  */
public static int [] copy1( int [] source) {
     int len = source.length;
     int [] result = new int [len];
 
     for ( int i = 0 ; i < len; i++) {
         result[i] = source[i];
     }
     return result;
}

方法二 : 使用System.arraycopy复制数组

/**
  * 使用System.arraycopy复制数组
  */
public static int [] copy2( int [] source) {
     int len = source.length;
     int [] result = new int [len];
     System.arraycopy(source, 0 , result, 0 , len);
     return result;
}

方法三 : 使用Arrays.copyOf复制数组

/**
  * 使用Arrays.copyOf复制数组
  */
public static int [] copy3( int [] source) {
     int len = source.length;
     int [] result = Arrays.copyOf(source, len);
     return result;
}

测试程序及结果如下:

         int [] source = new int [] { 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 };
System.out.println( "使用copy1方法" );
System.out.println(Arrays.toString(copy1(source)));
 
System.out.println( "使用copy2方法" );
System.out.println(Arrays.toString(copy2(source)));
 
System.out.println( "使用copy3方法" );
System.out.println(Arrays.toString(copy3(source)));
使用copy1方法
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
使用copy2方法
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
使用copy3方法
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

原文链接:http://thecodesample.com/?cat=26

更多例子请访问 : http://thecodesample.com/

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值