Why do we need the argument new String[0]
inside toArray
?
saved = getSharedPreferences("searches", MODE_PRIVATE);
String[] mystring = saved.getAll().keySet().toArray(new String[0]);
Why do we need the argument new String[0]
inside toArray
?
saved = getSharedPreferences("searches", MODE_PRIVATE);
String[] mystring = saved.getAll().keySet().toArray(new String[0]);
So that you get back a String[]
. The one without any argument gives back to you an Object[]
.
See you have 2 versions of this method:
By passing String[]
array, you are using the generic version.
A better way to pass the String[]
array would be to initialize it with the size of the Set
, and not with size 0, so that there is not need to create a new array in the method:
Set<String> set = saved.getAll().keySet();
String[] mystring = set.toArray(new String[set.size()]);
To add some more details to the accepted answer, some IDEs (IntelliJ here) give helpful comments and explanations to why they rise a warning on an active inspection when using new String[c.size()]
versus using new String[0]
as an argument of toArray
method:
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 (likec.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).
Hope it helps to further understand why things are done a certain way.
It's to provide a type for the return and prevent any compile-time ambiguity.
the signiture for that method call is: <T> T[] toArray(T[] a)
wheras the empty parameter one is Object[] toArray()