用Java写一个拷贝数组的方法
时间: 2024-06-05 13:06:40 浏览: 3
public static void copyArray(int[] source, int[] destination) {
if (source.length != destination.length) {
throw new IllegalArgumentException("Source and destination arrays must be of same length");
}
for (int i = 0; i < source.length; i++) {
destination[i] = source[i];
}
}
相关问题
写一个JAVA数组完整代码
以下是一个Java数组的完整代码示例:
public class Main {
public static void main(String[] args) {
// 创建数组
int[] arr = {1, 2, 3, 4, 5};
// 访问数组元素
System.out.println("第一个元素是:" + arr[0]);
System.out.println("最后一个元素是:" + arr[arr.length - 1]);
// 修改数组元素
arr[0] = 10;
System.out.println("修改后的第一个元素是:" + arr[0]);
// 循环遍历数组
for(int i = 0; i < arr.length; i++) {
System.out.println("第" + (i+1) + "个元素是:" + arr[i]);
}
// 数组排序
Arrays.sort(arr);
System.out.println("排序后的数组:");
System.out.println(Arrays.toString(arr));
// 查找数组元素是否存在
int index = Arrays.binarySearch(arr, 3);
System.out.println("元素3在数组中的位置是:" + index);
// 数组拷贝
int[] newArr = Arrays.copyOfRange(arr, 0, 3);
System.out.println("拷贝到新数组的前三个元素是:" + Arrays.toString(newArr));
}
}
在这段代码中,我们创建了一个整数类型的数组,然后演示了如何访问、修改、循环遍历、排序、查找元素位置和拷贝数组等操作。
用Java实现三种数组拷贝的方法
1. 使用for循环复制数组元素
```
public class ArrayCopyDemo {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = new int[arr1.length];
for (int i = 0; i < arr1.length; i++) {
arr2[i] = arr1[i];
}
System.out.println(Arrays.toString(arr2)); // [1, 2, 3, 4, 5]
}
}
```
2. 使用System类的arraycopy方法复制数组元素
```
public class ArrayCopyDemo {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = new int[arr1.length];
System.arraycopy(arr1, 0, arr2, 0, arr1.length);
System.out.println(Arrays.toString(arr2)); // [1, 2, 3, 4, 5]
}
}
```
3. 使用Arrays类的copyOf方法复制数组元素
```
public class ArrayCopyDemo {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = Arrays.copyOf(arr1, arr1.length);
System.out.println(Arrays.toString(arr2)); // [1, 2, 3, 4, 5]
}
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)