객체 지향 프로그래밍 - 참조 타입
배열 복사
한모로그
2023. 1. 15. 16:51
배열 복사하기
- 배열은 한 번 생성하면 길이를 변경할 수 없음. 더 많은 저장 공간이 필요하다면 더 큰 길이의 배열을 새로 만들고 이전 배열로부터 항목들을 복사해야 함.
출처, 이것이 자바다
package ch05.sec09;
public class ArrayCopyByForExample {
public static void main(String[] args) {
//길이가 3인 원본배열
int[] oldIntArray = {1, 2, 3};
//길이가 5인 사본배열
int[] newIntArray = new int[5];
//배열항목복사
for(int i=0; i<oldIntArray.length; i++) {
newIntArray[i] = oldIntArray[i];
}
//배열항목출력
for(int i=0; i<newIntArray.length; i++) {
System.out.print(newIntArray[i] + ", ");
}
}
}
- System의 arraycopy() 메소드를 이용해 배열 복사 가능
출처, 이것이 자바다
package ch05.sec09;
public class ArrayCopyExample {
public static void main(String[] args) {
//배열길이 3 -> 5 실행시 배열크기를 변경할 수가 없다.
String[] oldStrArray = {"Java", "array", "copy"};
//길이가 5인 배열을 새로 생성
String[] newStrArray = new String[5];
//배열항목 복사
System.arraycopy(oldStrArray, 0, newStrArray, 0, 3);
//배열항목 출력
for(int i=0; i<newStrArray.length; i++) {
System.out.print(newStrArray[i] + ", ");
}
}
}
실행 결과