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

后端 未结 2 440
暖寄归人
暖寄归人 2020-12-18 10:00

I am trying to convert a Set to an Array.

Set s = new HashSet(Arrays.asList(\"mango\",\"guava\",\"apple\"));
String[] a = s.toArr         


        
相关标签:
2条回答
  • 2020-12-18 10:05

    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;
     }
    
    0 讨论(0)
  • 2020-12-18 10:14

    The parameter is a result of one of the many well-known limitations in the Java generics system. Basically, the parameter is needed in order to be able to return an array of the correct type.

    0 讨论(0)
提交回复
热议问题