[java] 배열복사(Array copy)

[java] 배열복사(Array copy)

// 깊은복사 2. arraycopy() 메소드 이용

public void method3() {

// 새로운 배열을 생성한 후

// System. 클래스에서의 arryacopy() 메소드 호출

// 몇 번 인덱스부터 '몇개를' '어느 위치부터' 넣을건지 직접 지정 가능! ()안에 작성할거다!!!!!!!!!!

int [] origin = { 1 , 2 , 3 , 4 , 5 };

int [] copy = new int [ 10 ]; // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0

// [표현법] System.arraycopy(원본배열이름, 원본배열에서 복사를 시작할 인덱스,

// 복사본배열이름, 복사본배열에서 복사가 시작될 인덱스, 복사할 갯수);

System .arraycopy(origin, 0 , copy, 0 , 5 );

System .arraycopy(origin, 0 , copy, 1 , 5 );

//System.arraycopy(origin, 2, copy, 9, 2); // ArrayindexourofBounds! 방벖어!

System . out . println ( "-- 복사 출력 --" );

for ( int i = 0 ; i < = copy. length - 1 ; i + + ) {

System . out . print (copy[i] + " " );

}

System . out . println ( "

원본 배열의 해시코드 " + origin.hashCode());

System . out . println ( "복사본 배열의 해시코드 " + copy.hashCode());

}

// 깊은복사 3. copyOf() 메소드 사용

public void method4() {

// Arrays 클래스에서 제공하는 copyOf() 메소드

int [] origin = { 1 , 2 , 3 , 4 , 5 };

// [표현법] 복사본 배열 = Arrays.copyOf(원본배열이름, 복사할 객수);

int [] copy = Arrays.copyOf(origin, 10 );

System . out . println ( "-- 복사본배열 출력 --" );

for ( int i = 0 ; i < = copy. length - 1 ; i + + ) {

System . out . println (copy[i] + " " );

}

/*

*

* 2. System.arraycopy()

* 몇번 인덱스부터 몇개를 어느 위치의 인덱스에 복사할것인지 모두 지정 가능

*

* 3. Arrays.copyOf()

* 무조건 원본배열의 0번 인덱스부터 복사가 진행!!!(내가 지정한 갯수만큼!)

*/

}

// 깊은복사 4. clone() 메소드 이용

public void method5() {

// [표현법] 복사본 배열 이름 = 원본배열이름.clone();

int [] origin = { 1 , 2 , 3 , 4 , 5 };

//얕은복사

// int[] copy = origin;

//깊은복사

int [] copy = origin. clone ();

// 인덱스를 직접지정 X, 복사할 갯수 지정 X => 원본배열과 완전히 같다.

System . out . println (Arrays. toString (copy));

// toString => 예쁘게 좀 보자~

// Arrays.toString(내용을 출력하고 싶은 배열의 식별자를 입력);

// ex) [1, 2, 3, 4, 5]

}

from http://jjorong-e.tistory.com/27 by ccl(A) rewrite - 2021-10-24 06:02:11