Make copy of an array

前端 未结 11 2371
庸人自扰
庸人自扰 2020-11-21 23:05

I have an array a which is constantly being updated. Let\'s say a = [1,2,3,4,5]. I need to make an exact duplicate copy of a and call

11条回答
  •  名媛妹妹
    2020-11-21 23:30

    All solution that call length from array, add your code redundant null checkersconsider example:

    int[] a = {1,2,3,4,5};
    int[] b = Arrays.copyOf(a, a.length);
    int[] c = a.clone();
    
    //What if array a comes as local parameter? You need to use null check:
    
    public void someMethod(int[] a) {
        if (a!=null) {
            int[] b = Arrays.copyOf(a, a.length);
            int[] c = a.clone();
        }
    }
    

    I recommend you not inventing the wheel and use utility class where all necessary checks have already performed. Consider ArrayUtils from apache commons. You code become shorter:

    public void someMethod(int[] a) {
        int[] b = ArrayUtils.clone(a);
    }
    

    Apache commons you can find there

提交回复
热议问题