What does this syntax do, with square brackets around the number?
new Integer[0];
I've found it in a codebase I'm maintaining but I can't find any documentation on it. It is used like this:
Set<Form> forms = getForms();
List<Form> formsList = Arrays.asList(forms.toArray(new Form[0]))
It allocates an array with length zero; e.g. new Integer[0]
creates a zero length array of Integer
objects.
Why would you do that?
Well look at the javadocs for the form.toArray(T[])
method. Assuming that form
is some subtype of Collection
they are here.
The purpose of the toArray
method is to copy the elements of the target collection (e.g. your form
) into an array:
If the argument array is large enough to hold all elements, they are copied into that array. The result will be the argument array.
If the argument array is too small, a new array is allocated with the same type as the argument array and a length that is (just) enough to hold the elements. The elements are then copied into the new array, and it is returned as the result.
So what the code is actually doing is copying the elements of form
to an Integer[]
of the right size, and then wrapping the array to give a (fixed sized) List<Integer>
. This can then be passed to some other code without worrying that that code might alter the original form
collection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With