1

The implementation is for a linked list in 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.

1 Answer 1

4

An Object[] is not a sub-type of AnyType[] so the cast is illegal.

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)

So if you had a Class instance for the AnyType type:

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.

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:

Array.set(myPrimitiveArray, 0, myPrimitiveWrapperObject);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.