convert a linkedlist to an typed array

This should be a relatively straightforward question. But I've got this code where I want to convert a linked list to a typed array. I think it should work, but it's not compiling because of a class cast problem.

The method signature of setSelectedOptions takes Long[] arg1 but compiler is complaining because the list.toArray() signature returns Object[].

I checked this other question: How to convert linkedlist to array using `toArray()`? - and it indicates that toArray should be returning a typed list.

Can anyone advise why it's not working? (note I tried to cast the array parameter explicitly to Long[] and got a class cast exception)

if (selectedOptions == null)
{
    // set up the carrier delivery options transient option.
    List<Long> list = new LinkedList<Long>();
    for (CarrierDeliveryMethodOptionValue cdv: carrierOptionValues)
    {
        list.add(cdv.getId());
    }

    setSelectedOptions(list.toArray());
}
Jon Skeet
people
quotationmark

Basically you're using the wrong overload of toArray. You want the one accepting an array T[], which is declared to return a T[] as well. It uses the execution-time type of the array to work out the type of array to create - it can't do this without that extra information, because the LinkedList itself doesn't "know" its element type. (That's type erasure.)

You can pass an array of any length to it - it will create a new one if necessary - so this works:

setSelectedOptions(list.toArray(new Long[0]));

But for efficiency, you may want to pass one which is the right size already:

setSelectedOptions(list.toArray(new Long[list.size()]));

As ever with performance, you'll need to balance efficiency with readability depending on how much readability impact you think there is in calling size() vs how important the performance is in your context.

Note that if your setSelectedOptions method actually takes a long[] instead of a Long[], you'll need to convert the array separately - auto-unboxing only works for individual items, not whole arrays.

people

See more on this question at Stackoverflow