import java.util.Arrays;
public int[] copy(int[] source, int beginIndex, int endIndex){
return Arrays.copyOfRange(source,beginIndex,endIndex);
}
方法二:
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;
}
方法三:
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));
}
}