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?
There’s a method
Iterables.toArrayin Google Guava.Looking at the source, it’s defined as:
Where
ObjectArrays.newArrayeventually delegates to a method that looks like:So it looks like there’s no way to avoid the
@SuppressWarningsentirely, but you can and should at least constrain it to the smallest possible scope.Or, better yet, just use somebody else’s implementation!