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

前端 未结 7 1536
再見小時候
再見小時候 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:21
    Arrays.fill(arr, UN);
    
    0 讨论(0)
  • 2021-01-23 13:33

    No, not with the standard libraries. If you write your own functions, though, you can easily do so in a single statement (not instruction; those are different). Mine looks like String[][] strings = Arrayu.fill(new String[x][y], "");

    Here's a link. There's some junk in there too, though; I just posted a copy of the current source directly without cleaning it up.

    0 讨论(0)
  • 2021-01-23 13:33

    Oops, read your question better:

    You can init an array like so

    int[] arr = new int[] {UN, UN, UN, UN, UN};
    

    But ofcourse, if you don't know the size at compile time, then you have to do the for loop. The second technique is not possible.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-23 13:36

    No.

    Next question?

    0 讨论(0)
  • 2021-01-23 13:42
    int arr[] = { 0, 0, 0, 0, 0 };
    
    0 讨论(0)
提交回复
热议问题