Any shortcut to initialize all array elements to zero?

后端 未结 14 2736
北恋
北恋 2020-11-28 18:12

In C/C++ I used to do

int arr[10] = {0};

...to initialize all my array elements to 0.

Is there a similar shortcut in

14条回答
  •  温柔的废话
    2020-11-28 18:22

    In c/cpp there is no shortcut but to initialize all the arrays with the zero subscript.Ex:

      int arr[10] = {0};
    

    But in java there is a magic tool called Arrays.fill() which will fill all the values in an array with the integer of your choice.Ex:

      import java.util.Arrays;
    
        public class Main
        {
          public static void main(String[] args)
           {
             int ar[] = {2, 2, 1, 8, 3, 2, 2, 4, 2};
             Arrays.fill(ar, 10);
             System.out.println("Array completely filled" +                          
                " with 10\n" + Arrays.toString(ar));
       }
     }
    

提交回复
热议问题