What is the use of the new String [0] in toArray (new String [0]);

hi I have something like this:

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 ?

+8
java android
source share
2 answers

So, you will return to String[] . Anyone who has no arguments returns Object[] .

You have 2 versions of this method:

By passing the String[] array, you are using the generic version.


The best way to pass an array to String[] is to initialize it with a size of Set , rather than a size of 0, so there is no need to create a new array in the method:

 Set<String> set = saved.getAll().keySet(); String[] mystring = set.toArray(new String[set.size()]); 
+20
source share

It should provide a return type and prevent any compile-time ambiguity.

for this method call: <T> T[] toArray(T[] a)

if the empty parameter is Object[] toArray()

+3
source share

All Articles