There isn't a way to get rid of the unchecked or unsafe operations
warning, or creating a TypeSafe Array without editing your method signature.
See this bug report for the gory details.
One way is to pass in a pre-allocated Array of Type T
:
public class IterableHelp
{
public <T> T[] toArray(final T[] t, final Iterable<T> elements)
{
int i = 0;
for (final T element : elements)
{
t[i] = element;
}
return t;
}
}
This gets rid of the unchecked or unsafe
warning, but it also puts the onus on the calling class to create the array with the correct bounds to begin with which kind of defeats the purpose of your convenience method.
If you want to dynamically create a TypeSafe array, you really can't do it in a TypeSafe way in Java.
This works and compiles, but it doesn't solve the unchecked or unsafe cast issue, it just moves it to a different place. I had to add the @SuppressWarnings
annotation to get it to stop complaining about the cast.
@SuppressWarnings({"unchecked"})
public class IterableHelp
{
public <T> T[] toArray(Class<T> t, Iterable<T> elements)
{
final ArrayList<T> arrayElements = new ArrayList<T>();
for (T element : elements)
{
arrayElements.add(element);
}
final T[] ta = (T[]) Array.newInstance(t, arrayElements.size());
return arrayElements.toArray(ta);
}
}