산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> java

자바 복사 배열

자바 복사 배열

이 자습서에서는 예제를 통해 Java에서 배열(1차원 및 2차원 모두)을 복사하는 데 사용할 수 있는 다양한 방법에 대해 배웁니다.

Java에서는 하나의 배열을 다른 배열로 복사할 수 있습니다. Java에서 배열을 복사하는 데 사용할 수 있는 몇 가지 기술이 있습니다.

<시간>

1. 할당 연산자를 사용하여 배열 복사

예를 들어 보겠습니다.

class Main {
    public static void main(String[] args) {
       
        int [] numbers = {1, 2, 3, 4, 5, 6};
        int [] positiveNumbers = numbers;    // copying arrays

        for (int number: positiveNumbers) {
            System.out.print(number + ", ");
        }
    }
}

출력 :

1, 2, 3, 4, 5, 6

위의 예에서는 할당 연산자(= ) numbers라는 배열을 복사합니다. positiveNumbers라는 다른 배열로 .

이 기술은 가장 쉽고 효과적입니다. 그러나 이 기술에는 문제가 있습니다. 한 배열의 요소를 변경하면 다른 배열의 해당 요소도 변경됩니다. 예를 들어,

class Main {
    public static void main(String[] args) {
      
        int [] numbers = {1, 2, 3, 4, 5, 6};
        int [] positiveNumbers = numbers;    // copying arrays
      
        // change value of first array
        numbers[0] = -1;

        // printing the second array
        for (int number: positiveNumbers) {
            System.out.print(number + ", ");
        }
    }
}

출력 :

-1, 2, 3, 4, 5, 6

여기에서 숫자의 한 값이 변경되었음을 알 수 있습니다. 정렬. positiveNumbers를 출력할 때 배열에서도 동일한 값이 변경되었음을 알 수 있습니다.

두 배열이 동일한 배열 객체를 참조하기 때문입니다. 이것은 얕은 복사 때문입니다. 얕은 복사에 대해 자세히 알아보려면 얕은 복사를 방문하세요.

이제 배열을 복사하면서 새로운 배열 객체를 만들려면 얕은 복사가 아닌 깊은 복사가 필요합니다.

<시간>

2. 루프 구성을 사용하여 배열 복사

예를 들어 보겠습니다.

import java.util.Arrays;

class Main {
    public static void main(String[] args) {
      
        int [] source = {1, 2, 3, 4, 5, 6};
        int [] destination = new int[6];

        // iterate and copy elements from source to destination
        for (int i = 0; i < source.length; ++i) {
            destination[i] = source[i];
        }
      
         // converting array to string
        System.out.println(Arrays.toString(destination));
    }
}

출력 :

[1, 2, 3, 4, 5, 6]

위의 예에서는 for을 사용했습니다. 루프를 사용하여 소스 배열의 각 요소를 반복합니다. 각 반복에서 소스의 요소를 복사합니다. 대상에 대한 배열 배열.

여기에서 소스 및 대상 배열은 서로 다른 객체(딥 카피)를 참조합니다. 따라서 한 배열의 요소가 변경되면 다른 배열의 해당 요소는 변경되지 않습니다.

진술을 주목하십시오.

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

여기서 toString() 메서드는 배열을 문자열로 변환하는 데 사용됩니다. 자세한 내용은 toString() 메서드(공식 Java 설명서)를 참조하십시오.

<시간>

3. arraycopy() 메서드를 사용하여 배열 복사

Java에서 System 클래스에는 arraycopy()이라는 메서드가 포함되어 있습니다. 배열을 복사합니다. 이 방법은 위의 두 가지 방법보다 배열을 복사하는 더 나은 방법입니다.

arraycopy() 방법을 사용하면 소스 배열의 지정된 부분을 대상 배열로 복사할 수 있습니다. 예를 들어,

arraycopy(Object src, int srcPos,Object dest, int destPos, int length)

여기,

예를 들어 보겠습니다.

// To use Arrays.toString() method
import java.util.Arrays;

class Main {
    public static void main(String[] args) {
        int[] n1 = {2, 3, 12, 4, 12, -2};
      
        int[] n3 = new int[5];

        // Creating n2 array of having length of n1 array
        int[] n2 = new int[n1.length];
      
        // copying entire n1 array to n2
        System.arraycopy(n1, 0, n2, 0, n1.length);
        System.out.println("n2 = " + Arrays.toString(n2));  
      
        // copying elements from index 2 on n1 array
        // copying element to index 1 of n3 array
        // 2 elements will be copied
        System.arraycopy(n1, 2, n3, 1, 2);
        System.out.println("n3 = " + Arrays.toString(n3));  
    }
}

출력 :

n2 = [2, 3, 12, 4, 12, -2]
n3 = [0, 12, 4, 0, 0]

위의 예에서는 arraycopy()를 사용했습니다. 방법,

보시다시피 int 요소의 기본 초기값은 유형 배열은 0입니다.

<시간>

4. copyOfRange() 메서드를 사용하여 배열 복사

Java Arrays 클래스에 정의된 copyOfRange() 메서드를 사용하여 배열을 복사할 수도 있습니다. 예를 들어,

// To use toString() and copyOfRange() method
import java.util.Arrays;

class ArraysCopy {
    public static void main(String[] args) {
      
        int[] source = {2, 3, 12, 4, 12, -2};
      
        // copying entire source array to destination
        int[] destination1 = Arrays.copyOfRange(source, 0, source.length);      
        System.out.println("destination1 = " + Arrays.toString(destination1)); 
      
        // copying from index 2 to 5 (5 is not included) 
        int[] destination2 = Arrays.copyOfRange(source, 2, 5); 
        System.out.println("destination2 = " + Arrays.toString(destination2));   
    }
}

출력

destination1 = [2, 3, 12, 4, 12, -2]
destination2 = [12, 4, 12]

위의 예에서 줄을 주목하십시오.

int[] destination1 = Arrays.copyOfRange(source, 0, source.length);

여기에서 destination1을 생성하고 있음을 알 수 있습니다. 배열 및 소스 복사 동시에 배열합니다. destination1을 생성하지 않습니다. copyOfRange()을 호출하기 전에 배열 방법. 방법에 대해 자세히 알아보려면 Java copyOfRange를 방문하십시오.

<시간>

5. 루프를 사용하여 2차원 배열 복사하기

1차원 배열과 유사하게 for를 사용하여 2차원 배열을 복사할 수도 있습니다. 고리. 예를 들어,

import java.util.Arrays;

class Main {
    public static void main(String[] args) {
      
        int[][] source = {
              {1, 2, 3, 4}, 
              {5, 6},
              {0, 2, 42, -4, 5}
              };

        int[][] destination = new int[source.length][];

        for (int i = 0; i < destination.length; ++i) {

            // allocating space for each row of destination array
            destination[i] = new int[source[i].length];

            for (int j = 0; j < destination[i].length; ++j) {
                destination[i][j] = source[i][j];
            }
        }
     
        // displaying destination array
        System.out.println(Arrays.deepToString(destination));  
      
    }
}

출력 :

[[1, 2, 3, 4], [5, 6], [0, 2, 42, -4, 5]]

위의 프로그램에서 줄을 주목하십시오.

System.out.println(Arrays.deepToString(destination);

여기서 deepToString() 방법은 2차원 배열의 더 나은 표현을 제공하는 데 사용됩니다. 자세한 내용은 Java deepToString()을 참조하십시오.

<시간>

arraycopy()를 사용하여 2차원 배열 복사

위의 코드를 더 간단하게 만들기 위해 내부 루프를 System.arraycopy()로 바꿀 수 있습니다. 1차원 배열의 경우처럼. 예를 들어,

import java.util.Arrays;

class Main {
    public static void main(String[] args) {
      
        int[][] source = {
              {1, 2, 3, 4}, 
              {5, 6},
              {0, 2, 42, -4, 5}
              };

        int[][] destination = new int[source.length][];

        for (int i = 0; i < source.length; ++i) {

             // allocating space for each row of destination array
             destination[i] = new int[source[i].length];
             System.arraycopy(source[i], 0, destination[i], 0, destination[i].length);
        }
     
        // displaying destination array
        System.out.println(Arrays.deepToString(destination));      
    }
}

출력 :

[[1, 2, 3, 4], [5, 6], [0, 2, 42, -4, 5]]

여기에서 내부 for을 대체하여 동일한 출력을 얻는 것을 볼 수 있습니다. arraycopy() 루프 방법.


java

  1. C# 배열
  2. 자바 연산자
  3. 자바 주석
  4. 자바 인터페이스
  5. 자바 리소스 사용
  6. 자바 주석
  7. C++의 배열 | 선언 | 초기화 | 배열 예제에 대한 포인터
  8. 예제를 사용한 C++ 배열 동적 할당
  9. Java Arrays Tutorial:선언, 생성, 초기화 [예시]
  10. Java에서 객체 배열을 만드는 방법