Dejas Dejas - 6 days ago 6
Java Question

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

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?

Answer

There's a method Iterables.toArray in Google Guava.

Looking at the source, it's defined as:

  /**
   * Copies an iterable's elements into an array.
   *
   * @param iterable the iterable to copy
   * @param type the type of the elements
   * @return a newly-allocated array into which all the elements of the iterable
   *     have been copied
   */
  public static <T> T[] toArray(Iterable<? extends T> iterable, Class<T> type) {
    Collection<? extends T> collection = toCollection(iterable);
    T[] array = ObjectArrays.newArray(type, collection.size());
    return collection.toArray(array);
  }

Where ObjectArrays.newArray eventually delegates to a method that looks like:

  /**
   * Returns a new array of the given length with the specified component type.
   *
   * @param type the component type
   * @param length the length of the new array
   */
  @SuppressWarnings("unchecked")
  static <T> T[] newArray(Class<T> type, int length) {
    return (T[]) Array.newInstance(type, length);
  }

So it looks like there's no way to avoid the @SuppressWarnings entirely, but you can and should at least constrain it to the smallest possible scope.

Or, better yet, just use somebody else's implementation!

Comments