将Iterable <T>转换为T []的可重用方法?

Dej*_*jas 24 java generics

我正在尝试编写一个泛型方法来返回数组形式的Iterable的内容.

这是我有的:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

但我收到编译器警告'注意:...\IterableHelp.java使用未经检查或不安全的操作.

是否有任何关于避免这种警告的方法的想法?

Dan*_*den 27

Iterables.toArrayGoogle Guava中有一种方法.

查看源代码,定义为:

  /**
   * 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);
  }
Run Code Online (Sandbox Code Playgroud)

ObjectArrays.newArray最终代表们,看起来像一个方法:

  /**
   * 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);
  }
Run Code Online (Sandbox Code Playgroud)

所以看起来没有办法@SuppressWarnings完全避免,但你可以而且至少应该将它限制在尽可能小的范围内.

或者,更好的是,只需使用其他人的实现!