Convert ArrayList<String> to String[] array

This question already has an answer here:

  • Converting 'ArrayList<String> to 'String[]' in Java 13 answers

  • 像这样使用。

    List<String> stockList = new ArrayList<String>();
    stockList.add("stock1");
    stockList.add("stock2");
    
    String[] stockArr = new String[stockList.size()];
    stockArr = stockList.toArray(stockArr);
    
    for(String s : stockArr)
        System.out.println(s);
    

    尝试这个

    String[] arr = list.toArray(new String[list.size()]);
    

    What is happening is that stock_list.toArray() is creating an Object[] rather than a String[] and hence the typecast is failing1.

    The correct code would be:

      String [] stockArr = stockList.toArray(new String[stockList.size()]);
    

    or even

      String [] stockArr = stockList.toArray(new String[0]);
    

    (Surprisingly, the latter version is faster in recent Java releases: see https://stackoverflow.com/a/4042464/139985)

    For more details, refer to the javadocs for the two overloads of List.toArray .

    (From a technical perspective, the reason for this API behaviour / design is that an implementation of the List<T>.toArray() method has no information of what the <T> is at runtime. All it knows is that the raw element type is Object . By contrast, in the other case, the array parameter gives the base type of the array. (If the supplied array is big enough, it is used. Otherwise a new array of the same type and a larger size will be allocated and returned as the result.)


    1 - In Java, an Object[] is not assignment compatible with a String[] . If it was, then you could do this:

        Object[] objects = new Object[]{new Cat("fluffy")};
        Dog[] dogs = (Dog[]) objects;
        Dog d = dogs[0];     // Huh???
    

    This is clearly nonsense, and that is why array types are not generally assignment compatible.

    链接地址: http://www.djcxy.com/p/3366.html

    上一篇: 从内存分配的角度来看ArrayList vs LinkedList

    下一篇: 将ArrayList <String>转换为String []数组