The need for a new line [0] in the Set toArray () method

I am trying to convert Set to an array.

Set<String> s = new HashSet<String>(Arrays.asList("mango","guava","apple")); String[] a = s.toArray(new String[0]); for(String x:a) System.out.println(x); 

And it works great. But I do not understand the meaning of new String[0] in String[] a = s.toArray(new String[0]); .

At first I tried String[] a = c.toArray(); but it did not work. Why do we need new String[0] .

+4
source share
2 answers

This is the array into which the elements of the set should be stored, if it is large enough; otherwise, a new array of the same runtime type is allocated for this purpose.

Object [] toArray () returns an Object[] that cannot be passed to String[] or any other type array.

T [] toArray (T [] a) returns an array containing all the elements of this set; execution type of the returned array - the type of the specified array. If the set matches the specified array, it is returned in it. Otherwise, the type of the execution environment of the specified array and the size of this set are assigned to the new array.

If you execute the implementation code (I am posting the code from OpenJDK ), it will be clear to you:

  public <T> T[] toArray(T[] a) { if (a.length < size) // Make a new array of a runtime type, but my contents: return (T[]) Arrays.copyOf(elementData, size, a.getClass()); System.arraycopy(elementData, 0, a, 0, size); if (a.length > size) a[size] = null; return a; } 
+9
source

A parameter is the result of one of many known limitations in the Java generic system. In principle, this parameter is necessary to be able to return an array of the correct type.

+5
source

Source: https://habr.com/ru/post/1479890/


All Articles