What does new Boolean[0]
or new String[0]
in Java evaluate to?
Why do we need a number here ?
Which of the following is proper way?
myList.toArray(new Boolean[0])
or
myList.toArray(new Boolean[myList.size()])
What does new Boolean[0]
or new String[0]
in Java evaluate to?
Why do we need a number here ?
Which of the following is proper way?
myList.toArray(new Boolean[0])
or
myList.toArray(new Boolean[myList.size()])
Quoting JetBrains IntelliJ IDEA inspection tool hint:
There are two styles to convert a collection to an array: either using a pre-sized array (like c.toArray(new String[c.size()])) or using an empty array (like c.toArray(new String[0]).
In older Java versions using pre-sized array was recommended, as the reflection call which is necessary to create an array of proper size was quite slow. However since late updates of OpenJDK 6 this call was intrinsified, making the performance of the empty array version the same and sometimes even better, compared to the pre-sized version. Also passing pre-sized array is dangerous for a concurrent or synchronized collection as a data race is possible between the size and toArray call which may result in extra nulls at the end of the array, if the collection was concurrently shrunk during the operation.
This inspection allows to follow the uniform style: either using an empty array (which is recommended in modern Java) or using a pre-sized array (which might be faster in older Java versions or non-HotSpot based JVMs).
The expression new Boolean[0]
allocates memory for a new array object with a length of 0.
When you call myList.toArray(...)
, the toArray()
method will first check if the array that you provide is large enough. If it isn't, the method will then allocate a new array that is large enough.
So when you call myList.toArray(new Boolean[0])
, you are allocating a new array, then immediately after allocating another new array, and then the garbage collector can then free the first (useless) array.
When you call myList.toArray(new Boolean[myList.size()])
, you allocate an array of the necessary size and then fill it. This is more efficient both in terms of memory usage and CPU time. I always use this pattern, when it is convenient.
new Boolean[0]
creates an array of zero elements.
Instead
new Boolean[myList.size()]
creates an array that is the size of myList .
In the past, you should have used new Boolean[myList.size()]
because this was more efficient.
The first option meant that you were passing a zero-size array that would be discarded in order to create a new one.
However, as Eng.Fouad wrote using the InteliJ documentation, in the newest versions this is no long the case.