Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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]); 
like image 818
user2580401 Avatar asked Aug 08 '13 21:08

user2580401


People also ask

What is the use of toArray () in Java?

The toArray() method of ArrayList is used to return an array containing all the elements in ArrayList in the correct order.

How do you use the toArray method?

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.


1 Answers

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()]); 
like image 70
Rohit Jain Avatar answered Sep 17 '22 15:09

Rohit Jain