Arrays中copyOfRange 方法分析:

用Arrays中的方法复制一个数组:

public class Test1 {
    public static void main(String[] args) {

        int [] arr ={3,5,7,1,6,8,4};
        int [] newArr=Arrays.copyOfRange(arr, 1,4);
        for(int i : newArr){
            System.out.print(i+" ");
        }
    }
}

自己定义一个方法,将数组中从索引 from (包含 from )开始到索引 to 结束(不包含 to )的元素复制到新数组中,并将新数组返回

​
public class Test {


 public static void main(String[] args) {
            int [] arr={8,9,6,4,3,9,2,1};

        int [] result1=copyOfRange(arr,2,5);

       for(int i : result1){
        
            System.out.print(i+" ");
        }
}
 public static  int[] copyOfRange(int [] arr, int from ,int to){
        int [] arrNew1 =new int[to-from];

        for (int i = 0; i <=to - from +1; i++,from++) {    /*i=0; f=2, i<=4
                                                             i=1; f=3  i<=3
                                                             i=2; f=4; i<=2
                                                             i=3; f=5; i<=*/
            arrNew1[i] =arr[from];
        }
        return  arrNew1;

    }
}

​

在这儿在遍历,数组时候,记着,from 也是变化的;

猜你喜欢

转载自blog.csdn.net/yuwotongle1018/article/details/81149314