JAVA공부

[Java] 배열 복사 알아보기

코딩알파 2021. 10. 3. 19:39
728x90

 

배열은 한 번 생성하면 크기를 변경할 수 없기 때문에 더 큰 배열을 만들어서 이전 배열은 복사한다.

배열을 복사 방법은 2가지가 있다.

for문 과 System.arraycopy( ) 메서드를 사용한다.

for문

for문 배열 복사

 

 
public class javaStudyTest {
 
    public static void main(String[] args) {
    
        int[] oArray = {11,22,33};
        int[] nArray= new int[6];
        for(int i=0; i<oArray.length; i++) {
            nArray[i]=oArray[i];
            }
        
        for(int i=0; i<nArray.length; i++) {
            System.out.print(nArray[i]+" ");
        }
        
    
 
    }
 
}
 
cs

 

 
11 22 33 0 0 0 
cs

 

복사가 되지않은곳은 초기값으로 설정된다. int형은 초기값 0이다.

 

System.arraycopy ( ) 

 
System.arraycopy(oneObject , int oneFirst , twoObject , int twoFirst , int length);
cs

 

oneObject는 원본 배열이고 oneFirst는 원본 배열의 복사를 시작할 인덱스이다.

twoObject는 복사받을 배열이고 twoFirst는 복사받을 배열의 시작 인덱스이다.

length는 복사할 개수를 의미한다.

 

System.arraycopy 배열 복사

 

 
public class javaStudyTest {
 
    public static void main(String[] args) {
    
    int[] oneNum = {4,5,6};
    int[] twoNum = new int[6];
    
    System.arraycopy(oneNum,0,twoNum,0,oneNum.length);
    
    
    for(int i=0; i<twoNum.length; i++) {
        System.out.print(twoNum[i]+" ");
    }
 
    }
 
}
 
cs

 

 
4 5 6 0 0 0
cs

 

728x90