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

时光怂恿深爱的人放手 提交于 2019-12-02 06:04:52

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.

Arrays.fill(arr, UN);

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.

mwooten.dev

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.

No.

Next question?

int arr[] = { 0, 0, 0, 0, 0 };

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!