JAvaルーチン練習(配列コピーとarraycopy)


//    
public class Test {
	public static void main(String[] args) {
		
		String[] s = 
		{"Microsoft", "IBM", "Sun", "Oracle", "Apple"};
		
		String[] sCopy  = new String[6];
		
		System.arraycopy(s, 0, sCopy, 0, s.length);
		
		for(int i = 0; i < s.length; i++) {
			System.out.print(s[i] + " ");
		}
		System.out.println();
		
		for(int i = 0; i < sCopy.length; i++) {
			System.out.print(sCopy[i] + " ");
		}
		System.out.println();
			
		
		int [][] intArray = {{1, 2}, {1, 3, 4}, {4, 9}};
		int [][] intArrayCopy = new int [3][];
		System.arraycopy(intArray, 0, intArrayCopy, 0,intArray.length);
		
		
		//          
		intArrayCopy[2][1] = 100;
		for(int i = 0; i < intArray.length; i++) {
			for(int j = 0; j < intArray[i].length; j++) {
				System.out.print(intArray[i][j] + " ");
			}
			
			System.out.println();
		}
		
		//      !
	}
}

--------------------------------------------------------------------------------第2バージョン、 上記バージョンのほんの少しの最適化--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
public class TestArrayCopy {
	public static void main(String[] args) {
		String[] s = { "Microsoft", "IBM", "Sun", "Oracle", "Apple" };

		String[] sCopy = new String[6];

		System.arraycopy(s, 0, sCopy, 0, s.length);

		for (int i = 0; i < s.length; i++) {
			System.out.print(s[i] + " ");
		}

		System.out.println();

		for (int i = 0; i < sCopy.length; i++) {
			System.out.print(sCopy[i] + " ");
		}
		System.out.println();

		int[][] intArray = { { 1, 2 }, { 3, 4, 5 }, { 6, 7 } };
		int[][] intArrayCopy = new int[3][];
		System.arraycopy(intArray, 0, intArrayCopy, 0, intArray.length);
		
		/**
		 *  arraycopy      ,       !
		 */
		intArray[2][1] = 100;
		
		for(int i = 0; i < intArray.length;i++) {
			for(int j = 0; j < intArray[i].length;j ++) {
				System.out.print(intArray[i][j] + " ");
			}
			System.out.println();
		}
		System.out.println();
		
		for(int i = 0; i < intArrayCopy.length;i++) {
			for(int j = 0; j < intArrayCopy[i].length;j ++) {
				System.out.print(intArrayCopy[i][j] + " ");
			}
			System.out.println();
		}
	}
}