Java List toArray(T[] a) implementation

后端 未结 5 1370
挽巷
挽巷 2021-01-04 13:26

I was just looking at the method defined in the List interface:

Returns an array containing all of the elements in this list in the correct order; the

5条回答
  •  青春惊慌失措
    2021-01-04 13:51

    This method is a holdover from pre-1.5 Java. Here is the link to javadoc

    Back then it was the only way to convert a list to a reifiable array.

    It is an obscure fact, but although you can store anything in the Object[] array, you cannot cast this array to more specific type, e.g.

    Object[] generic_array = { "string" };
    
    String[] strings_array = generic_array; // ClassCastException
    

    Seemingly more efficient List.toArray() does just that, it creates a generic Object array.

    Before Java generics, the only way to do a type-safe transfer was to have this cludge:

    String[] stronglyTypedArrayFromList ( List strings )
    {
        return (String[]) strings.toArray( new String[] );
        // or another variant
        // return (String[]) strings.toArray( new String[ strings.size( ) ] );
    }
    

    Thankfully generics made these kind of machinations obsolete. This method was left there to provide backward compatibility with pre 1.5 code.

提交回复
热议问题