2020-02-22

Java Collection.toArray(IntFunction) Default Method

A new default method toArray(IntFunction) has been added to the java.util.Collection interface.

This method allows the collection's elements to be transferred to a newly created array of a desired runtime type. The new method is an overload of the existing toArray(T[]) method that takes an array instance as an argument. The addition of the overloaded method creates a minor source incompatibility. Previously, code of the form coll.toArray(null) would always resolve to the existing toArray method. With the new overloaded method, this code is now ambiguous and will result in a compile-time error. (This is only a source incompatibility. Existing binaries are unaffected.)

The ambiguous code should be changed to cast null to the desired array type, for example, toArray((Object[])null) or some other array type. Note that passing null to either toArray method is specified to throw NullPointerException.


No comments:

Post a Comment