提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
使用for循环和System.arraycopy()方法复制数组
import java.util.Arrays; public class Main { public static void main(String[] args) {/**来 自 nowjava**/ // Have an array with 5 elements int[] data = {1, 2, 3, 4, 5 }; // Expand the data array to 7 elements int[] d1 = expandArray(data, 7); // Truncate the data array to 3 elements int[] d2 = expandArray(data, 3); System.out.println("Original Array: " + Arrays.toString(data)); System.out.println("Expanded Array: " + Arrays.toString(d1)); System.out.println("Truncated Array: " + Arrays.toString(d2));// 来自 n o w j a v a . c o m // Copy data array to new arrays d1 = new int[9]; d2 = new int[2]; System.arraycopy(data, 0, d1, 0, 5); System.arraycopy(data, 0, d2, 0, 2); System.out.println("Original Array: " + Arrays.toString(data)); System.out.println("Expanded Array: " + Arrays.toString(d1)); System.out.println("Truncated Array: " + Arrays.toString(d2)); } public static int[] expandArray(int[] oldArray, int newLength) { int originalLength = oldArray.length; int[] newArray = new int[newLength]; int elementsToCopy = 0;