---
title: "数组复制的三种方法"
author: "MouseLearnJava"
date: "2014-11-30T12:57:30Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2014-11-30T12:57:30Z"
id: 2161917
url: "https://mouselearnjava.iteye.com/blog/2161917"
---

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

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

[帮助](http://thecodesample.com/?cat=26)

`/**`

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

`*/`

`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复制数组**

[帮助](http://thecodesample.com/?cat=26)

`/**`

`* 使用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复制数组**

[帮助](http://thecodesample.com/?cat=26)

`/**`

`* 使用Arrays.copyOf复制数组`

`*/`

`public` `static` `int[] copy3(int[] source) {`

`int` `len = source.length;`

`int[] result = Arrays.copyOf(source, len);`

`return` `result;`

`}`

测试程序及结果如下：

[帮助](http://thecodesample.com/?cat=26)

`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/?cat=26)

更多例子请访问 ： [http://thecodesample.com/](http://thecodesample.com/)