Java 转换Iterable的可重用方法<;T>;到T[]?

Java 转换Iterable的可重用方法<;T>;到T[]?,java,generics,Java,Generics,我正在尝试编写一个通用方法,以数组形式返回Iterable的内容 以下是我所拥有的: public class IterableHelp { public <T> T[] toArray(Iterable<T> elements) { ArrayList<T> arrayElements = new ArrayList<T>(); for(T element : elements) {

我正在尝试编写一个通用方法,以数组形式返回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();
    }
}
公共类ITerablehLP
{
公共T[]toArray(可替换元素)
{
ArrayList arrayElements=新的ArrayList();
对于(T元素:元素)
{
数组元素。添加(元素);
}
return(T[])arrayElements.toArray();
}
}
但我收到一条编译器警告:“注意:…\IterableHelp.java使用未经检查或不安全的操作。”


有没有其他方法可以避免这样的警告?

没有一种方法可以消除
未检查或不安全的操作
警告,或者在不编辑方法签名的情况下创建类型安全数组

见此了解血淋淋的细节

一种方法是传入类型为
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;
    }
}
谷歌番石榴中有一种方法

综上所述,它的定义如下:

  /**
   * 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);
  }
因此,似乎没有办法完全避免
@SuppressWarnings
,但您可以而且至少应该将其限制在尽可能小的范围内


或者,更好的方法是使用其他人的实现

您遇到了比未检查的警告更大的问题。事实上,如果T不是Object,它将在运行时抛出ClassCastException

尝试
String[]foo=IterableHelp.toArray(新的ArrayList())


简单地说,因为数组在运行时包含组件类型,所以要创建适当的T[],必须将组件类作为另一个参数传入(作为T或T[]本身的类,或者作为T或T[]的对象),并使用反射来创建数组。
Collection
toArray()
方法的形式,由于这个原因,它接受一个参数,接受一个T[]对象。

我假设警告在最后一行,您将数组强制转换为
T[]
?另请参见番石榴的
Iterables.toArray(Iterable
  /**
   * 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);
  }
  /**
   * 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);
  }