Any shortcut to initialize all array elements to zero?

后端 未结 14 2567
北恋
北恋 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:47

    Initialization is not require in case of zero because default value of int in Java is zero. For values other than zero java.util.Arrays provides a number of options, simplest one is fill method.

    int[] arr = new int[5];
    Arrays.fill(arr, -1);
    System.out.println(Arrays.toString(arr));  //[-1, -1, -1, -1, -1 ]
    
    int [] arr = new int[5];
    // fill value 1 from index 0, inclusive, to index 3, exclusive
    Arrays.fill(arr, 0, 3, -1 )
    System.out.println(Arrays.toString(arr)); // [-1, -1, -1, 0, 0]
    

    We can also use Arrays.setAll() if we want to fill value on condition basis:

    int[] array = new int[20];
    Arrays.setAll(array, p -> p > 10 ? -1 : p);
    
    int[] arr = new int[5];
    Arrays.setAll(arr, i -> i);
    System.out.println(Arrays.toString(arr));   // [0, 1, 2, 3, 4]
    
    0 讨论(0)
  • 2020-11-28 18:49

    declare the array as instance variable in the class i.e. out of every method and JVM will give it 0 as default value. You need not to worry anymore

    0 讨论(0)
提交回复
热议问题