简体   繁体   English

在java中转换泛型数组

[英]casting a generic array in java

The implementation is for a linked list in java : 该实现是针对java中的链表:

public AnyType[] toArr() {

        AnyType[] arr = (AnyType[]) new Object[size];

        int i = 0;
        Node<AnyType> current = head.next;
        while (cur != head){

            arr[i] = current.data;// fill the array
            i++;
            current = current.next;

        }      

    return arr;

}

public static void main(String[] args) {
    System.out.println(ll.toArr().toString());
} 

The error that I get: 我得到的错误:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;

Thanks. 谢谢。

An Object[] is not a sub-type of AnyType[] so the cast is illegal. Object[]不是AnyType[]的子类型,因此AnyType[]是非法的。

To create an array of a particular type, you can use the reflective java.lang.reflect.Array.newInstance factory method : http://download.oracle.com/javase/1.5.0/docs/api/java/lang/reflect/Array.html#newInstance(java.lang.Class,%20int ) 要创建特定类型的数组,可以使用反射java.lang.reflect.Array.newInstance工厂方法: http//download.oracle.com/javase/1.5.0/docs/api/java/lang/ reflect / Array.html #newInstance(java.lang.Class,%20int

So if you had a Class instance for the AnyType type: 因此,如果您有AnyType类型的Class实例:

Class<? extends AnyType> anyTypeClass = ...;
AnyType[] newArray = (AnyType[]) Array.newInstance(anyTypeClass, length);

If you want to deal with primitive types, you can do that with java.lang.reflect.Array . 如果要处理原始类型,可以使用java.lang.reflect.Array

Object myPrimitiveArray = Array.newInstance(Integer.TYPE, length);

but since you can't cast it to an Object[] you need to use reflection to modify it as well: 但由于你不能将它强制转换为Object[]你还需要使用反射来修改它:

Array.set(myPrimitiveArray, 0, myPrimitiveWrapperObject);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM