Java二维数组动态扩展的简单实现

// 二维数组动态扩展的简单实现(规则数组)
// 使用System.arraycopy(from, fromIndex, to, toIndex, count)方法 

public class DynamicArray 
{
	private static final int MAX = 4;



	public static void main(String[] args) 
	{
		int[][] arr1 = new int[MAX][MAX];

		//数组初始化
		for (int i = 0; i < arr1.length; i++)
		{
			for (int j = 0; j < arr1[i].length; j++)
			{
				arr1[i][j] = 9;
			}
		}
		print(arr1);	//打印原数组
		int[][] arr2 = extendsArray(arr1);
		System.out.println("------------------");
		print(arr2);	//打印扩展后数组
	}

	public static int[][] extendsArray(int[][] array)
	{
		int[][] arr = new int[array.length * 2][array[0].length * 2];		//扩展为原来两倍
		for(int i = 0; i < array.length; i++)
		{
			System.arraycopy(array[i], 0, arr[i], 0, array[i].length);	//数组拷贝
		}
		return arr;
	}

	//打印输出
	public static void print(int[][] arr)
	{
		for (int[] a: arr)
		{
			for (int item: a)
			{
				System.out.print(item + " ");
			}
			System.out.println();
		}
	}
}

结果:

9 9 9 9
9 9 9 9
9 9 9 9
9 9 9 9
------------------
9 9 9 9 0 0 0 0
9 9 9 9 0 0 0 0
9 9 9 9 0 0 0 0
9 9 9 9 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0

你可能感兴趣的:(Java)