ITeye博客

数组复制的三种方法

MouseLearnJava · 2014-11-30 12:57 · Java · 编程语言 · Markdown

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

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

帮助

/**

* 循环遍历赋值达到复制数组的效果

*/

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/

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。