Can I declare and initialize an array with the same instruction in Java?

前端 未结 7 1539
再見小時候
再見小時候 2021-01-23 12:57

Is there a way to do the following at the same time?

static final int UN = 0; // uninitialized nodes
int[] arr;

// ... code ...

arr = new int[size];
for (int i         


        
7条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-23 13:43

    You don't need to initialize them with 0. An int defaults to 0 already.

    Just

    int[] array = new int[size];
    

    is enough. It gives you an array of zeroes of the given length. If it were an Integer[], it would have been an array of nulls.

提交回复
热议问题