What's the use of new String[0] in 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:

  • 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()]);

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()

Tags:

Java

Android