Collection.toArray(IntFunction)

Zhong Yu zhong.j.yu at gmail.com
Thu Jun 13 07:40:47 PDT 2013


On Thu, Jun 13, 2013 at 2:09 AM, Remi Forax <forax at univ-mlv.fr> wrote:
> On 06/13/2013 07:33 AM, Zhong Yu wrote:
>> On Thu, May 30, 2013 at 3:14 AM, Stephen Colebourne
>> <scolebourne at joda.org> wrote:
>>> On 30 May 2013 08:30, Peter Levart <peter.levart at gmail.com> wrote:
>>>> String[] y = x.toArray(String[]::new);
>>> Thats very nice ;-)
>>> Stephen
>>>
>> Hmm...
>>      toArray(new String[0])
>>      toArray(String[]::new)
>> not too much difference in syntax. Try to explain it to a newbie:)
>
> Apart from the coloncolon syntax (::), it's easy either you give the
> size or not.
>
>>
>> I wish we could have something like this:
>>
>>     interface Collection<E>
>>     {
>>          @SafeVarargs
>>          E[] array(E... array);
>>     }
>>
>>      Collection<String> x = ...;
>>      x.array();
>>
>> This works because an empty String[] is passed in as the arg.
>
> Without discussing about the restrictions on @SafeVarargs,  It depends
> what you mean by it works, if it's apart creating a big hole in the type
> safety of all programs because this method allows to create arrays of
> parametrized types which are unsafe, I agree with you, it works :)

I think creating generic arrays is safe, as safe as instantiating
generic Lists; what is unsafe is up-casting generic arrays in a way
that loses type arguments, e.g. List<String>[] -> List[]. Java should
allow the 1st case, and raise a warning for the 2nd case.

Zhong Yu


More information about the lambda-dev mailing list