Can I declare and initialize an array with the sam

2019-02-28 10:35发布

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 = 0; i < 5; i++) {
    arr[i] = UN;
}

Basically, I want to declare arr once I know what its size will be and initialize it to UN without having to loop. So something like this:

int[] arr = new int[size] = UN;

Is this possible?

Thanks.

7条回答
够拽才男人
2楼-- · 2019-02-28 10:44

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.

查看更多
家丑人穷心不美
3楼-- · 2019-02-28 10:48

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.

查看更多
【Aperson】
4楼-- · 2019-02-28 11:01

No.

Next question?

查看更多
混吃等死
5楼-- · 2019-02-28 11:01

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.

查看更多
神经病院院长
6楼-- · 2019-02-28 11:02

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.

查看更多
成全新的幸福
7楼-- · 2019-02-28 11:06
Arrays.fill(arr, UN);
查看更多
登录 后发表回答