Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
537 views
in Technique[技术] by (71.8m points)

java - Need for new String[0] in the Set toArray() method

I am trying to convert a 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 fine. But I don't understand the significance of new String[0] in String[] a = s.toArray(new String[0]);.

I mean initially I was trying String[] a = c.toArray();, but it wan't working. Why is the need for new String[0].

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is the array into which the elements of the Set are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.

Object[] toArray(), returns an Object[] which cannot be cast to String[] or any other type array.

T[] toArray(T[] a) , returns an array containing all of the elements in this set; the runtime type of the returned array is that of the specified array. If the set fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this set.

If you go through the implementing code (I'm posting the code from OpenJDK) , it will be clear for you :

 public <T> T[] toArray(T[] a) {
     if (a.length < size)
     // Make a new array of a's 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;
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...