Why is `Stream.collect` type-safe and `Stream.toArray(IntFunction)` is not?

前端 未结 1 1354
感动是毒
感动是毒 2020-12-30 02:43

Consider the following code fragment

String strings[] = {\"test\"};
final List collect = java.util.Arrays.stream(strings).collect(java.util.str         


        
相关标签:
1条回答
  • 2020-12-30 03:11

    The signature of the method Stream::toArray looks as follows. Please note that the type parameters T and A are completely unrelated.

    public interface Stream<T> {
        <A> A[] toArray(IntFunction<A[]> generator);
    }
    

    In the source of ReferencePipeline.java, you can find the following comment:

    Since A has no relation to U (not possible to declare that A is an upper bound of U) there will be no static type checking. Therefore use a raw type and assume A == U rather than propagating the separation of A and U throughout the code-base. The runtime type of U is never checked for equality with the component type of the runtime type of A[]. Runtime checking will be performed when an element is stored in A[], thus if A is not a super type of U an ArrayStoreException will be thrown.

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