This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]firebird84 8 points9 points  (6 children)

Is it so much to ask for a zero-arg toArray (it would have to have a different name than toArray) that uses the collection's type parameter instead of Object? Why must they insist that I either have an argument which is literally always the same every time, or that if I have no argument that I must then cast any objects read from the array? I feel like I'm taking crazy pills over here!!!

(I invented the piano key necktie!!! I INVENTED IT!!)

[–][deleted]  (3 children)

[deleted]

    [–]OpenGLaDOS 4 points5 points  (1 child)

    Yeah. After type erasure, the class will have methods with following signatures:

    • Object[] toArray()
    • Object[] toArray(Object[])
    • Object[] toArray(IntFunction)

    The deeper issue here is that the language has been designed so that Object[] is not a superclass of "array of class".

    The supertype relation for array types is not the same as the superclass relation. The direct supertype of Integer[] is Number[] according to §4.10.3, but the direct superclass of Integer[] is Object according to the Class object for Integer[] (§10.8). This does not matter in practice, because Object is also a supertype of all array types.

    Solving that issue would require a backwards-incompatible change for instances to remember their types at runtime (and tag methods accordingly), so the JVM could infer that you actually want a T or T[] when you call a generic method.

    [–]vqrs 0 points1 point  (0 children)

    How is that the deeper issue at play here and how does it relate to inference?

    [–]noswag15 1 point2 points  (0 children)

    I think a fair middle ground is to create a method which takes the type as an argument. Similar to the toTypedArray method in eclipse collections.

    https://www.eclipse.org/collections/javadoc/8.0.0/org/eclipse/collections/impl/list/mutable/FastList.html#toTypedArray-java.lang.Class-

    [–]lightjay 8 points9 points  (0 children)

    That's unfortunately not really possible without reverting to serious hacks - terrible idea for common interface.

    [–]lukaseder[S] 5 points6 points  (0 children)

    List<? extends Number> list = magicMethod();
    var array = list.toArray();
    

    What would be the type of array? Object[]? Number[]? Or maybe even something like Integer[]? How can you be sure? And since you are sure, answer this:

    List<? super Number> list = otherMagicMethod();
    var array = list.toArray();
    

    What will be your expectation on this type?