【问题标题】:Creating generic arrays in Java在 Java 中创建泛型数组
【发布时间】:2010-10-25 10:31:50
【问题描述】:
public K[] toArray()
{
    K[] result = (K[])new Object[this.size()];
    int index  = 0;
    for(K k : this)
        result[index++] = k;
    return result;
}

这段代码好像不行,会抛出异常:

java.lang.ClassCastException: [Ljava.lang.Object;不能转换为 ...

谁能告诉我如何创建一个泛型类型的数组? 谢谢。

【问题讨论】:

标签: java arrays generics casting


【解决方案1】:

你不能:你必须将类作为参数传递:

public <K> K[] toArray(Class<K> clazz)
{
    K[] result = (K[])Array.newInstance(clazz,this.size());
    int index  = 0;
    for(K k : this)
        result[index++] = k;
    return result;
}

【讨论】:

    【解决方案2】:

    好的,这不起作用 K[] 结果 = 新 K[this.size()];

    如果你能上课。那么:

      Class claz;
      Test(Class m) {
         claz = m;
      }
    
      <K>  K[] toArray() { 
    K[] array=(K[])Array.newInstance(claz,this.size());
    return array;
    }
    

    【讨论】:

      【解决方案3】:

      您的代码会引发该异常,因为它实际上为您提供了一个Object 类型的数组。 Maurice Perry 的代码有效,但转换为 K[ ] 将导致警告,因为在这种情况下,由于类型擦除,编译器无法保证类型安全。但是,您可以执行以下操作。

      import java.util.ArrayList;  
      import java.lang.reflect.Array;  
      
      public class ExtremeCoder<K> extends ArrayList<K>  
      {  
         public K[ ] toArray(Class<K[ ]> clazz)  
         {  
            K[ ] result = clazz.cast(Array.newInstance(clazz.getComponentType( ), this.size( )));  
            int index = 0;  
            for(K k : this)  
               result[index++] = k;  
            return result;  
         }  
      }
      

      这将为您提供所需类型的数组,并保证类型安全。 my answer 对不久前的一个类似问题进行了深入解释。

      【讨论】:

        猜你喜欢
        • 2011-07-22
        • 1970-01-01
        • 1970-01-01
        • 2011-07-23
        • 2011-10-27
        • 1970-01-01
        • 2022-01-02
        相关资源
        最近更新 更多