beginIndex 아래 첨자에서 시작하여 endIndex 아래 첨자에서 끝나는 지정된 소스 배열 소스를 복사하려면 copy 메서드를 작성하십시오.

beginIndex 아래 첨자에서 시작하여 endIndex 아래 첨자에서 끝나는 지정된 소스 배열 소스를 복사하려면 copy 메서드를 작성하십시오.

방법 1:

import java.util.Arrays;

public int[] copy(int[] source, int beginIndex, int endIndex){
     return Arrays.copyOfRange(source,beginIndex,endIndex);

}

방법 2:

import java.util.Arrays;

public int[] copy(int[] source, int beginIndex, int endIndex){
     if (endIndex < beginIndex){
            throw new IllegalArgumentException("beginIndex > endIndex");
        }

        if (beginIndex < 0){
            throw new ArrayIndexOutOfBoundsException("beginIndex < 0");
        }

        int[] result = new int[endIndex - beginIndex];
        System.arraycopy(source,beginIndex,result,0,(endIndex - beginIndex > source.length ? source.length : endIndex - beginIndex));
        return result;

}

방법 3:

import java.util.Arrays;

public int[] copy(int[] source, int beginIndex, int endIndex){
     if (endIndex < beginIndex){
            throw new IllegalArgumentException("beginIndex > endIndex");
        }

        if (beginIndex < 0){
            throw new ArrayIndexOutOfBoundsException("beginIndex < 0");
        }

        int count = endIndex - beginIndex;
        int[] result = new int[count];

        if (count > source.length) {
            count = source.length;
        }

        for (int i = 0; i < count; i++) {
            result[i] = source[beginIndex + i];
        }
        return result;
}

 주요 방법:

import java.util.Arrays;

public class Main10 {
    //10.请编写方法copy,复制指定源数组source,从beginIndex下标开始,到endIndex下标结束。
    public static void main(String[] args) {
        int[] array = {1,2,3,4,5};
        Functions f = new Functions();
        int[] result = f.copy(array,0,6);
        System.out.println(Arrays.toString(result));
    }
}

추천

출처blog.csdn.net/chen_kai_fa/article/details/123674989