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

android, java

Solution

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

Problem

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]); ```

Original source

Related problems