Reusable method to transform Iterable<T> to T[]?

Viewed 11563

I'm trying to write a generic method to return the contents of an Iterable in array form.

Here is what I have:

public class IterableHelp
{
    public <T> T[] toArray(Iterable<T> elements)
    {
        ArrayList<T> arrayElements = new ArrayList<T>();
        for(T element : elements)
        {
            arrayElements.add(element);
        }

        return (T[])arrayElements.toArray();
    }
}

But I'm getting a compiler warning 'Note: ...\IterableHelp.java uses unchecked or unsafe operations.'

Any thoughts on another approach that would avoid such a warning?

3 Answers
Related