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

前端 未结 7 1538
再見小時候
再見小時候 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:34

    Well, in the case of objects (or primitives with autoboxing) you can do the following:

    int count = 20;
    final int UN = 0;
    Integer[] values = Collections.nCopies(count, UN).toArray(new Integer[count]);
    

    The downsides are that you have to use the object forms of the primitives (since the Collections must be of objects) and a separate List will be constructed and then thrown away. This would allow you to create the array as one statement however.

提交回复
热议问题