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]);
The toArray() method of ArrayList is used to return an array containing all the elements in ArrayList in the correct order.
public <T> T[] toArray(T[] a)The toArray() method is used to get an array which contains all the elements in ArrayList object in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein.
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:
Object[] toArray()
<T> T[] toArray(T[] a)
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()]);
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